angular2 ngFor从ngOnInit()上的api获取数据时不起作用

Kri*_*hna 5 angular2-observables angular

comment.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'
import { Comment } from 'comment entity path'
import {CommentService} from 'comment service path'
import { Observable } from 'rxjs/Observable';
@Component({
    template: ` <ul><li *ngFor="let comment of comments|async"> {{comment.Name}}</li></ul>`
})
export class CommentComponent implements OnInit {
    comments: Observable<comment[]>;  

    constructor(private router: Router, private commentService: CommentService) {
    }

    ngOnInit() {
        this.comments = this.getComments();
    }

    getComments() {
        return this.commentService.getComments();
    }

}
Run Code Online (Sandbox Code Playgroud)

comment.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Comment } from 'comment path here';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class CommentService {
    private commentUrl = 'api path';  // URL to web api

    constructor(private http: Http) {
    }

    getComments(): Observable<Comment[]> {
        return this.http.get(this.commentUrl).map(
            (response) => {
                let data = response.text() ? response.json():[{}];
                if (data) {
                    console.log(data);
                    return data;
                }
                return data;
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

ngOnInit方法中,我能够获取注释列表,但问题是该列表未ngFor在HTML上使用绑定。这是因为HTML在响应之前呈现。但是在刷新页面时,数据会自动绑定。我想念什么吗?

Jul*_*ian 0

试试这个
模板:<ul><li *ngFor="let comment of comments|async"> {{comment.Name}}</li></ul>

comments: Observable<comment[]>;  
    ngOnInit() {      
       this.comments = this.getComments();
    }

    getComments() {      
     return this.commentService.getComments();   
   }
Run Code Online (Sandbox Code Playgroud)

我在您的代码中看到两个问题 1.您调用 map 而不返回任何值。2.您尝试在地图内设置值而不是订阅,但一旦到达 ngOnInit 中的订阅,这些值就未定义