开发者问题收集

Typescript / Angular2:转换 JSON 以与 Observable 和 JSONP 交互

2016-05-13
15577

我想将我的 json 数组转换为我创建的界面,并希望在浏览器中显示它。我认为我的界面可能出了问题,但我搞不清楚... 我需要更改什么才能运行我的代码?

界面:

 export interface Video {
  id: number;
  name: string;
  description: string;
  createdAt: string;
}

app.ts

import {JSONP_PROVIDERS, Jsonp} from '@angular/http';
import {Observable} from '../../../node_modules/rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';
import {Video} from './networking/api';

    private videoData: Observable<Video[]>;
    ngOnInit() {
                this.displayNewstVideo(10);
            }

            private displayNewstVideo(count: number) {
                this.videoData = this.jsonp
                .get('localhost:8080/video/newst/' + count + '?jsonp=JSONP_CALLBACK')
                .map(res => (res.json() as Video[]));
                alert(this.videoData.count);
            }

app.html

<div class="container">
  <div class="video" style="font-family:sans-serif" *ngFor="#entry of videoData | async;  #i = index">
      <br *ngIf="i > 0" />
      <span class="title" style="font-size:1.2rem">
        <span>{{i + 1}}. </span>
        <a href={{entry.urlDesktop}}>{{entry.name}}</a>
      </span>
      <span> ({{entry.description}})</span>
      <div>Submitted at {{entry.createdAt * 1000 | date:"mediumTime"}}.</div>
    </div>

JSON

[{
id: 1,
name: "Some Name",
description: "BlaBla",
createdAt: "2016-05-04 13:30:01.0",
},
{
id: 2,
name: "Some Name",
description: "BlaBla",
createdAt: "2016-05-04 13:30:01.0",
}]

编辑

  1. 我已在 chrome 中的网络选项卡中检查了请求是否正确,并且它按预期工作:200 OK -->响应也很好
  2. 我按照 Thierry 的说法编辑了我的代码,现在它终于显示了我的数组中的第一个对象 :-)!!但现在我收到以下错误:

Uncaught EXCEPTION: Error in app/html/app.html:27:11 ORIGINAL EXCEPTION: RangeError: Provided date is not in valid range. ORIGINAL STACKTRACE: RangeError: Provided date is not in valid range. at boundformat (native) at Function.DateFormatter.format ( http://localhost:3000/node_modules/@angular/common/src/facade/intl.js:100:26 ) at DatePipe.transform ( http://localhost:3000/node_modules/@angular/common/src/pipes/date_pipe.js:25:37 ) at eval ( http://localhost:3000/node_modules/@angular/core/src/linker/view_utils.js:188:22 ) at DebugAppView._View_AppComponent1.detectChangesInternal (AppComponent.template.js:377:148) at DebugAppView.AppView.detectChanges ( http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14 ) at DebugAppView.detectChanges ( http://localhost:3000/node_modules/@angular/core/src/linker/view.js:289:44 ) at DebugAppView.AppView.detectContentChildrenChanges ( http://localhost:3000/node_modules/@angular/core/src/linker/view.js:215:37 ) at DebugAppView._View_AppComponent0.detectChangesInternal (AppComponent.template.js:198:8) at DebugAppView.AppView.detectChanges ( http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14 ) ERROR CONTEXT: [object Object]

3个回答

您可以尝试以下方法:

this.videoData = this.jsonp
    .get('localhost:8080/video/newst/' + count +
                      '?jsonp=JSONP_CALLBACK')
            .map(res => <Video[]>res.json();

编辑

我认为您的请求返回的不是 JSONP 内容,而是传统内容 (JSON)。如果是这样,您可以尝试以下方法:

import { bootstrap }  from 'angular2/platform/browser';
import { Component } from 'angular2/core';
import { HTTP_PROVIDERS, Http } from 'angular2/http';
import "rxjs/add/operator/map";

@Component({
  selector: "app",
  templateUrl: "app.html",
  providers: [HTTP_PROVIDERS]
})
class App {
  private feedData: Observable<Video[]>;

  constructor(private http: Http) { }

  ngOnInit() {
    this.displayNewstVideo(10);
  }

  private displayNewstVideo(count: number) {
    this.videoData = this.http
      .get('localhost:8080/video/newst/' + count)
      .map(res => (res.json() as Video[]))
      .do(videoData => {
        console.log(videoData);
      });
  }
}

bootstrap(App);
Thierry Templier
2016-05-13

尝试使用类而不是接口,因此在这种情况下 video.model.ts 将是:

export class Video {
  constructor(
    public id: number,
    public name: string,
    public description: string,
    public createdAt: string){}
}
wolfhoundjesse
2016-05-13

我最近做了一个 TypeScript 的演示,这让我想起了幻灯片的标题“没有接口!”在 TypeScript 中,当您定义 接口 时,它实际上编译为无。这可能有点误导。不过我想我明白你想做什么:

问题是 JSONP 对象返回的方式,它被填充了。所以它位于索引 [1] 中。试试这个:

this.videoData = this.jsonp
    .get('localhost:8080/video/newst/' + count +
                      '?jsonp=JSONP_CALLBACK')
            .map(res => <Video[]>res.json()[1]);
David Pine
2016-05-13