未访问Angular2(rc.6)JSON对象键
我正在开始我的第一个Angular2(rc.6)项目。 我有一个JSON对象已成功发送到组件,但我无法在模板中访问其键值 服务(摘录):未访问Angular2(rc.6)JSON对象键,json,angular,angular2-observables,Json,Angular,Angular2 Observables,我正在开始我的第一个Angular2(rc.6)项目。 我有一个JSON对象已成功发送到组件,但我无法在模板中访问其键值 服务(摘录): @Injectable() 出口级服务{ 构造函数(私有http:http){} getSong(id:number):承诺{ 让url='/maxapirest/v1/maxmusic/song/'+id console.log(url) 返回此文件。http .get(url) .toPromise() .然后(功能(响应){ log(response.j
@Injectable()
出口级服务{
构造函数(私有http:http){}
getSong(id:number):承诺{
让url='/maxapirest/v1/maxmusic/song/'+id
console.log(url)
返回此文件。http
.get(url)
.toPromise()
.然后(功能(响应){
log(response.json());
返回response.json();
} )
}
组成部分(节选):
@组件({
选择器:'我的歌曲阅读',
templateUrl:STATIC_URL+'song-reading.component.html',
提供者:[歌曲服务],
})
导出类SongReadingComponent实现OnInit{
宋:承诺;
建造师(
私人歌曲服务:歌曲服务,
专用路由:ActivatedRoute){}
ngOnInit():void{
this.route.params.forEach((params:params)=>{
if(参数['id']!==未定义){
设id=+params['id'];
this.song=this.songService.getSong(id)
}
});
}
~
模板(摘录):
{{song | async | json}
{{song.title | async}}
{{song.image | async}
{{song.id | async}
我无法理解的问题是{{song | json}}正确地输出了一个json对象:
{“id”:71,“title”:“它没有任何意义”…}
并且不会抛出错误。
但其他var键无论如何都不会被渲染
有什么想法吗?您需要使用
。然后(…)
,然后在那里赋值:
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
if (params['id'] !== undefined) {
let id = +params['id'];
this.songService.getSong(id)
.then(json => {
this.song = json;
});
}
});
}
你有什么发现吗?查一下
console.log(this.song)
?没错。谢谢!我没有考虑承诺周期…当然,我还必须将song:Promise;改为song:{};
@Component({
selector: 'my-song-reading',
templateUrl: STATIC_URL+'song-reading.component.html',
providers: [ SongService ],
})
export class SongReadingComponent implements OnInit {
song: Promise<Song>;
constructor(
private songService: SongService,
private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
if (params['id'] !== undefined) {
let id = +params['id'];
this.song = this.songService.getSong(id)
}
});
}
<div *ngIf="song">
{{ song | async | json }}<br/><br/><br/>
{{ song.title | async}}
{{ song.image | async }}
{{ song.id | async}}
</div>
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
if (params['id'] !== undefined) {
let id = +params['id'];
this.songService.getSong(id)
.then(json => {
this.song = json;
});
}
});
}