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';
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;
});
}
}
Inside the method, ngOnInitI can get a list of comments, but the problem is that the list is optional using ngForHTML. This is because HTML renders before the response. But when updating the page data is automatically linked. Did I miss something?
source
share