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

Posted

技术标签:

【中文标题】Typescript / Angular2:将 JSON 转换为与 Observable 和 JSONP 接口【英文标题】:Typescript / Angular2: Cast JSON to interface with Observable & JSONP 【发布时间】:2016-09-09 19:47:23 【问题描述】:

我想将我的 json-array 转换为我创建的界面,并希望在浏览器中显示它。我认为我的界面可能有问题,但我无法弄清楚... 我需要更改什么才能让我的代码运行?

界面:

 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",
]

编辑

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

未捕获的异常:app/html/app.html:27:11 中的错误 原始异常: RangeError:提供的日期不在有效范围内。 原始堆栈跟踪: RangeError:提供的日期不在有效范围内。 在 boundformat (本机) 在 Function.DateFormatter.format (http://localhost:3000/node_modules/@angular/common/src/facade/intl.js:100:26) 在 DatePipe.transform (http://localhost: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._View_AppComponent1.detectChangesInternal (AppComponent.template.js:377:148) 在 DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14) 在 DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:289:44) 在 DebugAppView.AppView.detectContentChildrenChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:215:37) 在 DebugAppView._View_AppComponent0.detectChangesInternal (AppComponent.template.js:198:8) 在 DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14) 错误上下文: [对象对象]

【问题讨论】:

【参考方案1】:

您可以尝试以下方法:

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

【讨论】:

感谢您的提示 - 遗憾的是它没有用...您还有其他想法吗? 它不起作用是什么意思? ;-) 你有错误吗?此外,您的警报应该移动到 do 运算符中...在您的情况下,它在执行时就在那里。 我想将我的 json 解析到我的界面中,然后我想在我的 html 中显示我的界面内容。但我没有得到任何编译器错误或其他东西。事实上,我是 Typescript 和 Angular2 的新手。 实际上 res.json() 会解析 JSON 内容。接口仅在设计时用于类型检查。它们不在运行时使用。你的数据显示了吗? 您对显示的内容有何理解?我的 html 在我的浏览器中保持空白 - 不显示任何内容。顺便说一句,我从这里得到了这样的想法:github.com/Microsoft/typescript-build2016-demos/tree/master/…【参考方案2】:

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

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

【讨论】:

【参考方案3】:

我最近做了一个TypeScript的介绍,这让我想起了幻灯片的标题“没有界面!”在 TypeScript 中,当您定义 interface 时,它实际上编译为空。这可能有点误导。我想我明白你想要做什么:

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

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

【讨论】:

以上是关于Typescript / Angular2:将 JSON 转换为与 Observable 和 JSONP 接口的主要内容,如果未能解决你的问题,请参考以下文章

Angular2,Typescript:如何将对象数组推入另一个对象数组,其中只有几个对象字段

如何将 TypeScript WebPack ts-loader 与 Angular2 @View 样式集成?

typescript 一个示例,显示动态地将模板注入Angular2组件的方式

降级使用 Typescript 编写的 angular2 组件。如何将其导入用 es5 编写的 angular 1 项目?

Typescript - 如何在 Angular2 中正确使用 jsPDF?

使用 angular2/typescript 从 html 生成 PDF 文件