angular2 ng在ngOnInit()从api获取数据时不起作用
发布时间:2020-12-17 10:24:39 所属栏目:安全 来源:网络整理
导读: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
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在响应之前呈现.但是刷新页面数据会自动绑定.我错过了什么吗?
试试这个
模板:< ul>< li * ngFor =“发表评论评论| async”> {{comment.Name}}< /立GT;< / UL> comments: Observable<comment[]>; ngOnInit() { this.comments = this.getComments(); } getComments() { return this.commentService.getComments(); } 我在你的代码中看到了2个问题1.您调用map而不返回任何值.2.您尝试在map中设置值而不是subscribe,但是一旦在ngOnInit中达到订阅,这些值就是未定义的 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |