简体   繁体   English

Typescript / Angular2:将JSON转换为与Observable和JSONP的接口

[英]Typescript / Angular2: Cast JSON to interface with Observable & JSONP

I'd like to cast my json-array to my interface which I've created and like to display it in the browser. 我想将我的json-array转换为我创建的界面,并希望在浏览器中显示它。 I think there is probably something wrong with my interface but I can't figure it out... What do I need to change to get my code running? 我认为我的界面可能有问题,但我无法弄明白...... 我需要更改什么来让我的代码运行?

Interface: 接口:

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

app.ts 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 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 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",
}]

Edits 编辑

  1. I've checked if the request is correct in my network-tab in chrome and it is working as excepted: 200 OK --> Response ist also fine 我已经检查了我的网络选项卡中的请求是否正确,并且它正常工作:200 OK - >响应也很好
  2. I edited my code as Thierry stated out and now it is finally showing the first object in my array :-)!! 我按照Thierry的说法编辑了我的代码,现在它终于显示了我的数组中的第一个对象:-) !! But I get following error now: 但我现在得到以下错误:

Uncaught EXCEPTION: Error in app/html/app.html:27:11 ORIGINAL EXCEPTION: RangeError: Provided date is not in valid range. 未捕获的EXCEPTION:app / html / app.html中的错误:27:11原始异常:RangeError:提供的日期不在有效范围内。 ORIGINAL STACKTRACE: RangeError: Provided date is not in valid range. ORIGINAL STACKTRACE:RangeError:提供的日期不在有效范围内。 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 ) ERRO at atatformat (native)at Function.DateFormatter.format( http:// localhost:3000/node_modules/@angular/common/src/facade/intl.js:100:26 )at DatePipe.transform( http:// localhost:在eval上的3000/node_modules/@angular/common/src/pipes/date_pipe.js:25:37 )( http:// localhost:3000/node_modules/@angular/core/src/linker/view_utils.js:188:22 )在DebugAppView.AppView.detectChanges的DebugAppView._View_AppComponent1.detectChangesInternal(AppComponent.template.js:377:148)中( http:// localhost:3000/node_modules/@angular/core/src/linker/view.js:200: 14 )在DebugAppView.AppView.detectContentChildrenChanges( http :// localhost:3000 / node_modules )的DebugAppView.detectChanges( http:// localhost:3000/node_modules/@angular/core/src/linker/view.js:289:44 )处/@angular/core/src/linker/view.js:215:37 )在DebugAppView.AppView.detectChanges( http:// localhost:3000 / )的DebugAppView._View_AppComponent0.detectChangesInternal(AppComponent.template.js:198:8)中node_modules/@angular/core/src/linker/view.js:200:14 )ERRO R CONTEXT: [object Object] R语境:[对象]

You could try the following instead: 您可以尝试以下方式:

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

Edit 编辑

I think that your request doesn't return JSONP content but classical one (JSON). 我认为您的请求不会返回JSONP内容,而是返回JSONP内容(JSON)。 If so, you could try the following: 如果是这样,您可以尝试以下方法:

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);

Try using a class instead of an interface, so in this case video.model.ts would be: 尝试使用类而不是接口,所以在这种情况下video.model.ts将是:

export class Video {
  constructor(
    public id: number,
    public name: string,
    public description: string,
    public createdAt: string){}
}

I gave a presentation of TypeScript recently, this reminded me of what of the slide's titles "There is no interface!" 我最近做了一个TypeScript的演示,这让我想起幻灯片的标题是什么“没有界面!” In TypeScript when you define an interface , it actually compiles down to nothing. TypeScript中定义interface ,它实际上会编译为空。 Which can be somewhat misleading. 这可能有点误导。 I think I understand what you're trying to do though: 我想我明白你要做的是:

The issue is the way that the JSONP object comes back, it's padded. 问题是JSONP对象返回的方式,它是填充的。 So it sits in the index [1] . 所以它位于索引[1] Try this instead: 试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM