【问题标题】:error promise unresolbed angular 2错误承诺未解决的角度2
【发布时间】:2016-09-24 21:27:47
【问题描述】:

我从 Angular 2 文档中了解到 ngOnInit 方法是从服务器获取数据的地方,所以我做什么但有问题:

组件

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

        });
  }
}

服务

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

如果我从模板中删除div*ngIf,我会得到一个未解决的promise 错误,这意味着模板是在promise 解决之前呈现的,所以冠军是未定义的。

但我发现将需要从服务器获取数据的每个组件都包装在 div*ngIf 中非常令人不安。

我做错了吗??

感谢和抱歉我的英语不好

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果您不想对 HTML 中的值进行任何检查,那么在呈现 HTML 之前让所有数据都可用会很有用,对吧?

    幸运的是,Angular2 使用resolve route guard 使这一切成为可能。它将阻止组件加载,直到满足可以加载数据的条件。然后,数据将在您的组件加载时立即可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多