karim karim - 2 months ago 26
TypeScript Question

error promise unresolbed angular 2

i learned from angular 2 doc that ngOnInit method is the place to fetch data from server so that what i do but there is problem :

component

import { Component, OnInit } from '@angular/core';

import { Champion } from './champion'

import { ChampionService } from './champion.service';

import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'champion',
template:
`
<div *ngIf="champion">
<h1> {{ champion.name }} </h1>

this is champion descirption
</div>
`,


})

export class ChampionComponent implements OnInit {

champion : Champion;

constructor(private championService : ChampionService,
private activatedRoute : ActivatedRoute)
{

}

ngOnInit() {
this.activatedRoute.params
.forEach(params => {
let id = +params['id']

this.championService.getChampion(id)
.then(champion => this.champion = champion);

});
}
}


service

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Champion } from './champion'


@Injectable()
export class ChampionService {

private url : string = "https://jsonplaceholder.typicode.com/users";

constructor(private http : Http) {

}

getChampions() : Promise<Champion[]> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Champion[]);
}

getChampion(id : number) : Promise<Champion> {
return this.http.get("https://jsonplaceholder.typicode.com/users/" + id)
.toPromise()
.then(response => {
return response.json() as Champion
})
}
}


if i remove the
div
with
*ngIf
from the template i get a unresolved promise error, that mean that the template is rendered before the promise is resolved, so champion is undifined.

but i found its very disturbing to wrap every componenat that need to fetch data from a server in a
div
with
*ngIf
.

i'm doing it wrong??

thanks and sorry for my bad english

Answer

If you want don't want to do some any checking for values in your HTML, it would be useful to have all the data already available to you before you render the HTML, right?

Fortunately, Angular2 makes exactly that possible with the the resolve route guard. It will keep a component from loading until a condition is met, which can be loading data. Then the data will be available to your component right when it loads.

Comments