映射服务返回的数据

时间:2017-09-13 15:35:32

标签: angular

在服务中有一个返回数据的方法,在调试时我可以在运行时看到“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 ]

BlogPost

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 - 最终让它发挥作用]
在重新阅读了几个关于可观察量的例子后,我只是把事情弄得太复杂了。所以现在,我的ngOnInit如下所示。

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

1 个答案:

答案 0 :(得分:1)

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

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

然后在你的ui中你可以使用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);
}