【问题标题】:Mapping data returned from service从服务返回的映射数据
【发布时间】:2017-09-13 15:35:31
【问题描述】:

在服务中有一个返回数据的方法,在调试时我可以在运行时看到“res”变量中的数据

getBlogPosts(): Observable<BlogPost[]> {
    var headers = new Headers();        
    headers.append('Content-Type', 'application/json');        
    return this.http.post("http://dlocal.test.com/api/fNet/GetBlogPosts",
        { postDate: '', bodyContent: '', Title: '' })          
        .map((res: Response) => {
            return <BlogPost[]>res.json();
        }).catch(this.handleError);
}

从 API 返回的数据示例:

[{
    "Id": 1,
    "Title": "title1",
    "BodyContent": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. test",
    "TagList": null,
    "DateCreated": "2017-09-13T00:00:00",
    "DateUpdated": "2017-09-13T00:00:00",
    "CreatedByUser": null,
    "UpdatedByUser": null
}, {
    "Id": 2,
    "Title": "title2",
    "BodyContent": "lkj kjlkaj lkjlaksdjf lkj kljlkj",
    "TagList": null,
    "DateCreated": "2017-09-13T00:00:00",
    "DateUpdated": "2017-09-13T00:00:00",
    "CreatedByUser": null,
    "UpdatedByUser": null
}]

但是,对于调用此服务的组件,我认为我没有做正确的事情来查看返回的值。成员“数据”未定义。我做错了什么?

getBlogPosts() {
    this.blogService.getBlogPosts()
        .subscribe((data) => {
            this.BlogPostList = data;
        });        
}

[ 更新 2 ]

组件:

ngOnInit(): void { 
    this.blogService.getBlogPosts()
      .subscribe((data: BlogPost[]) => {
      this.BlogPostList = <BlogPost[]>data;               
    }); 
}

服务方式:

getBlogPosts(): Observable<BlogPost[]> {
    var headers = new Headers();        
    headers.append('Content-Type', 'application/json');        
    return this.http.post("http://dlocal.test.com/api/fNet/GetBlogPosts",
        { postDate: '', bodyContent: '', Title: '' })
        .map(response => response.json())
        .catch(this.handleError);
}

模板

<div *ngFor="let b of BlogPostList" class="col-md-5">
   Title= {{b.title}}
</div>




让我们再试一次:
无法使用任何类型进行连接。我可以看到正在返回的数据,但它不会映射,并且 BlogPostList 导致 ngOnInit 内部未定义。在阅读了有关 Observables 的示例后,我认为我理解了这些内容。我想我没有

[ 更新 3 ]

博文

import { IBlogPostModel } from "./interfaces";

export class BlogPost implements IBlogPostModel{

    Id: number;
    Title: string;
    BodyContent: string;
    TagList: string;
    DateCreated: string;
    DateUpdated: string;
    CreatedUser: string;
    UpdatedUser: string;

    constructor(values: Object = {}) 
    { 
        Object.assign(this, values);

    }
};

组件

import { Component,OnInit } from '@angular/core';
import { ItBlogService } from './itdept.blog.service';
import { BlogPost } from '../model/blogpost';
import { Observable } from 'rxjs/Observable';


@Component({
    selector: 'itdept',
    templateUrl: 'app/itdept/itdept.component.html'
})
export class ItdeptComponent {

    public name: string;
    public BlogPostList: BlogPost[] = new Array<BlogPost>();

    constructor(private blogService: ItBlogService) {      

    }

    ngOnInit(): void {
        this.blogService.getBlogPosts()
            .subscribe(data => {
                this.BlogPostList = <BlogPost[]>data;
                //return <BlogPost[]>data;
            });    
    }

}

服务:

import { Injectable } from '@angular/core';
import { Http,Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { BlogPost } from '../model/blogpost';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import {User} from './user';



@Injectable()
export class ItBlogService {

    _baseUrl: string = '';

    constructor(private http:Http) {
        console.log('ItDeptBlogService Service created.', http);
    }

     getBlogPosts(): Observable<BlogPost[]> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post("http://dlocal.test.com/api/fNet/GetBlogPosts",
            { postDate: '', bodyContent: '', Title: '' })
            .map(response => response.json())
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json() || 'Server error');
    }

组件模板

<div *ngFor="let b of BlogPostList" class="col-md-5">
   Title= {{b.bodyContent}}
</div>

[ 更新 4 - 终于让它工作了]
在重新阅读了几个关于 observables 的例子之后,我只是让事情变得过于复杂。所以现在,我的 ngOnInit 如下所示。

ngOnInit(): void {
    this.blogService.getBlogPosts()
        .subscribe(data => {
            this.BlogPostList = data;
            console.log(data);
            console.log("test");
            //return <BlogPost[]>data;
        });    
}

【问题讨论】:

  • 在您的组件中,您正在调用 getBlogPosts() 中的服务方法,并且您确定此方法被称为某些 Wehre。
  • 是的,我的 API 上有一个名为 GetBlogPosts 的方法。

标签: angular


【解决方案1】:

如果您尝试在 html 中的 Ui 中显示这些数据,您可以使用异步管道,而不是将它们存储在变量中并在 html 中使用该变量。

this.BlogPostList = this.blogService.getBlogPosts()
    .map((data) => {
        return data;
    });        

然后在你的用户界面中你可以使用async pipe

<div *ngFor="let blog of BlogPostList"> ... </div>

如果你正在与打字打架,那么先用任何一个测试,然后你可以调整打字

getBlogPosts(): Observable<any> {
    var headers = new Headers();        
    headers.append('Content-Type', 'application/json');        
    return this.http.post("http://dlocal.test.com/api/fNet/GetBlogPosts",
        { postDate: '', bodyContent: '', Title: '' })
        .map(response => response.json())
        .catch(this.handleError);
}

【讨论】:

  • 不要认为这会起作用,因为服务的返回是一个可观察的,它需要将数据映射到一个类型(在这种情况下是 BlogPost[] 或 BlogPostList),对吗?
  • 一旦这些都编译好了,都是javascript。在 --aot build 之后都是一样的。所以打字只是编码时间
  • 如果我按照你的建议做,我会在 BlogPostList 上得到一个红色下划线,说 Observable 不能分配给 BlogPost[]
  • 当然不会编译。但是如果你同时做any 那么它会起作用。我在说这些是打字,不能在浏览器中运行,
  • 感谢您的帮助。在再次查看了一堆关于 observables 的东西之后,我能够让我的代码正常工作。我的麻烦主要在于映射。我知道 LINQ 并且这种语法对我来说并不陌生,但是与 RxJS 相关的语义仍然是我要掌握的东西。表面之下有大量的功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 2019-07-06
  • 2017-06-17
  • 2012-08-07
  • 1970-01-01
相关资源
最近更新 更多