Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 第2条承诺问题_Typescript_Angular_Es6 Promise - Fatal编程技术网

Typescript 第2条承诺问题

Typescript 第2条承诺问题,typescript,angular,es6-promise,Typescript,Angular,Es6 Promise,我开始学习Angular 2,但我在使用Promise.com时遇到了问题。然后从服务返回我的对象。我目前只使用固定数组(Coach)来伪造数据库调用。我服务的功能如下 getCoach(id: number) { return Promise.resolve(COACHES).then( coaches => coaches.filter(coach => coach.id == id)[0] ); } 然后,我在Ngonit钩子中的coach_d

我开始学习Angular 2,但我在使用Promise.com时遇到了问题。然后从服务返回我的对象。我目前只使用固定数组(Coach)来伪造数据库调用。我服务的功能如下

getCoach(id: number) {
    return Promise.resolve(COACHES).then(
        coaches => coaches.filter(coach => coach.id == id)[0]
    );
}
然后,我在Ngonit钩子中的coach_detail.component.ts中使用它,以使用Route Params获得我想要的coach对象:

export class CoachDetailComponent implements OnInit {

    coach: Coach;

    constructor(
        private _coachService: CoachService,
        private _routeParams: RouteParams) {}

    ngOnInit() {
        let id = +this._routeParams.get('id');
        this._coachService.getCoach(id).then(coach => this.coach = coach);
        console.log(this.coach);
    }
}
我可以在我的控制台中看到承诺返回到我的组件,但是
console.log(this.coach)
返回为
undefined

非常感谢您的帮助,因为我在不同的组件中使用了类似的逻辑来返回整个Coach列表,这很好

在检查承诺链之前调用您的
console.log()

ngOnInit() {
    let id = +this._routeParams.get('id');
    this._coachService.getCoach(id).then(coach => { 
      this.coach = coach 
      console.log(this.coach); // not undefined
    });
    console.log(this.coach); // undefined
}

但我不是在组件中定义的“coach”变量上调用console.log吗?
this.\u coachService.getCoach(id)
应该将返回的对象分配给
this.coach
。我的问题是我的arrow函数没有正确赋值,你的代码看起来很好。您能用示例创建一个plunker吗?出现这个问题是因为您在分配它之前正在使用
coach
。创建组件时,在调用
ngOnInit()
之前,模板尝试访问此变量。你可以在你的模板中使用
{{coach?.first_name}{{coach?.nam姓氏}}
看看它是ng2的“redux模式”的一个实现。一开始可能有点让人不知所措,但花每一个小时(或每周:)试图弄清楚它是值得的(;这只是工作原理-它有一些内部检查
if(isBlank(this.\u different)和&isPresent(value))
。。。