本文介绍了angular2 ngFor从ngOnInit()上的api获取数据时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

}

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

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

Within ngOnInit method I am able to get list of comments but the problem is the list is not binding using ngFor on the HTML. This is because HTML is rendering before the response. But On refreshing page data binds automatically. Am I missing something?

推荐答案

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

Try this
template: <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();   
   }

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

I see 2 problems in your code1. You call map without returning any value.2. You try to set values inside map instead of subscribe but the values was undefined once it reach subscribe in your ngOnInit

这篇关于angular2 ngFor从ngOnInit()上的api获取数据时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:17