Angular2 (rc.6) JSON 对象键未被访问
Angular2 (rc.6) JSON object keys not being accessed
我正在开始我的第一个 Angular2 (rc.6) 项目。
我有一个 JSON 对象已成功发送到组件,但我无法在模板中访问它的键值。
服务(摘录):
@Injectable()
export class SongService {
constructor(private http: Http) { }
getSong(id: number): Promise<Song> {
let url = '/maxapirest/v1/maxmusic/song/'+id
console.log(url)
return this.http
.get(url)
.toPromise()
.then(function(response) {
console.log(response.json());
return response.json();
} )
}
组件(摘录):
@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>
我无法弄清楚的问题是 {{ song | json }} 正确输出一个 JSON 对象:
{ "id": 71, "title": "It Don't Mean A Thing" ... }
并且不会抛出任何错误。
但是其他 var 键没有被渲染。
有什么想法吗?
你需要使用.then(...)
,然后在那里赋值:
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;
});
}
});
}
我正在开始我的第一个 Angular2 (rc.6) 项目。 我有一个 JSON 对象已成功发送到组件,但我无法在模板中访问它的键值。
服务(摘录):
@Injectable()
export class SongService {
constructor(private http: Http) { }
getSong(id: number): Promise<Song> {
let url = '/maxapirest/v1/maxmusic/song/'+id
console.log(url)
return this.http
.get(url)
.toPromise()
.then(function(response) {
console.log(response.json());
return response.json();
} )
}
组件(摘录):
@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>
我无法弄清楚的问题是 {{ song | json }} 正确输出一个 JSON 对象: { "id": 71, "title": "It Don't Mean A Thing" ... } 并且不会抛出任何错误。 但是其他 var 键没有被渲染。
有什么想法吗?
你需要使用.then(...)
,然后在那里赋值:
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;
});
}
});
}