Cruclax Cruclax - 2 months ago 11
JSON Question

Angular2 (rc.6) JSON object keys not being accessed

I'm starting my first Angular2 (rc.6) project.
I have a JSON object successfully being sent to a component but I cannot access its keys values in the template.

SERVICE (excerpt):

@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 (excerpt):

@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)
}
});

}


~

TEMPLATE (excerpt):

<div *ngIf="song">
{{ song | async | json }}<br/><br/><br/>
{{ song.title | async}}
{{ song.image | async }}
{{ song.id | async}}
</div>


The issue I cannot figure out is that {{ song | json }} correctly outputs a JSON object:
{ "id": 71, "title": "It Don't Mean A Thing" ... }
And no error is thrown.
But the other var keys are not rendered whatsoever.

Any ideas?

Answer

You need to use .then(...) and then assign the value there:

  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;
        });
      }
    });
  }