karim karim - 9 months ago 78
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 :


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

import { Champion } from './champion'

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

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

selector: 'champion',
<div *ngIf="champion">
<h1> {{ champion.name }} </h1>

this is champion descirption


export class ChampionComponent implements OnInit {

champion : Champion;

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


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

.then(champion => this.champion = champion);



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

import 'rxjs/add/operator/toPromise';

import { Champion } from './champion'

export class ChampionService {

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

constructor(private http : Http) {


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

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

if i remove the
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

i'm doing it wrong??

thanks and sorry for my bad english


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.