1

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?

1
  • do you get anything ?check with console.log(this.song)? Commented Sep 12, 2016 at 18:06

1 Answer 1

1

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;
        });
      }
    });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Thanks! I wasn't taking in account the Promise cycle... Of course I also had to change song: Promise<Song>; to song: {};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.