我是Angular 2的新手,我试图从网址中提取数据。 我的组件代码是:
import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import {ArticleService} from "../services/ArticleService";
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.css'],
providers: [ArticleService]
})
export class ArticleComponent implements OnInit {
article: JSON;
constructor(
private ArticleService: ArticleService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.ArticleService.getArticle(+params['id']))
.subscribe(art => {
this.article = art;
});
}
}
我的Article.service.ts是:
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ArticleService {
private headers = new Headers({'Content-Type': 'application/json'});
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: Http) {
}
getArticle(id: number) {
const url = `${this.apiUrl}/${id}`;
return this.http.get(url)
.map(response => response.json());
}
}
如果我在.subscribe()块中使用console.log(this.article)
,它会显示该对象,但如果在外面使用则显示未定义,因此我无法在我的html模板中使用该数据。
答案 0 :(得分:1)
使用安全导航(猫王)操作员
<div>{{article?.name}}</div>
或将article
与*ngIf
<div *ngIf="article">
<div>{{article.name}}</div>
</div>
答案 1 :(得分:0)
您应该考虑为您的文章创建一个界面,而不是指定类型JSON。我甚至都不知道这是一种内置类型。