angularjs – Angular 2 observable不会“映射”到模型
发布时间:2020-12-17 07:54:45 所属栏目:安全 来源:网络整理
导读:当我学习Angular 2时,我使用了一个observable来通过API获取一些数据.喜欢这个: getPosts() { return this.http.get(this._postsUrl) .map(res = Post[]res.json()) .catch(this.handleError); } 我的帖子模型看起来是这样的: export class Post {construct
当我学习Angular 2时,我使用了一个observable来通过API获取一些数据.喜欢这个:
getPosts() { return this.http.get(this._postsUrl) .map(res => <Post[]>res.json()) .catch(this.handleError); } 我的帖子模型看起来是这样的: export class Post { constructor( public title: string,public content: string,public img: string = 'test') { } 我面临的问题是地图运算符对Post模型没有任何作用.例如,我尝试为img值设置默认值,但在视图post.img中没有显示任何内容.我甚至用其他模型(Message [])更改了Post [],并且行为没有改变.任何人都可以解释这种行为吗?
当我想在模板中使用计算属性时,我遇到了类似的问题.
我在本文中找到了一个很好的解决方案: http://chariotsolutions.com/blog/post/angular-2-beta-0-somnambulant-inauguration-lands-small-app-rxjs-typescript/ 您在模型上创建一个静态方法,该方法接受一个对象数组,然后从映射函数中调用该方法.在静态方法中,您可以调用已经定义的构造函数或使用复制构造函数: 映射方法 getPosts() { return this.http.get(this._postsUrl) .map(res => Post.fromJSONArray(res.json())) .catch(this.handleError); } 现有的构造函数 export class Post { // Existing constructor. constructor(public title:string,public content:string,public img:string = 'test') {} // New static method. static fromJSONArray(array: Array<Object>): Post[] { return array.map(obj => new Post(obj['title'],obj['content'],obj['img'])); } } 复制构造函数 export class Post { title:string; content:string; img:string; // Copy constructor. constructor(obj: Object) { this.title = obj['title']; this.content = obj['content']; this.img = obj['img'] || 'test'; } // New static method. static fromJSONArray(array: Array<Object>): Post[] { return array.map(obj => new Post(obj); } } 如果您使用的是支持代码完成的编辑器,则可以将obj和数组参数的类型更改为Post: export class Post { title:string; content:string; img:string; // Copy constructor. constructor(obj: Post) { this.title = obj.title; this.content = obj.content; this.img = obj.img || 'test'; } // New static method. static fromJSONArray(array: Array<Post>): Post[] { return array.map(obj => new Post(obj); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |