角度承诺后设置标题

时间:2016-10-10 12:01:57

标签: angular angular-promise

我正在尝试学习角度所以我刚刚完成了heroes tutorial

然后我想我会改变这个,以便我可以更改每页的文档标题。所以我按照说明添加了title service

这在我的仪表板页面上工作得很好,我可以在初始化中调用标题服务,所以我想我会尝试将它添加到我的英雄详情页面,看看我是否可以使文档标题为大侠的名字:

import { Component, Input, OnInit } from '@angular/core';
import { Title }                    from '@angular/platform-browser';
import { ActivatedRoute, Params }   from '@angular/router';
import { Location }                 from '@angular/common';

import { Hero }                     from '../classes/hero';
import { HeroService }              from '../services/hero.service';

@Component({
    selector: 'my-hero-details',
    templateUrl: '/app/templates/hero-details.component.template.html'
})

export class HeroDetailsComponent implements OnInit {
    @Input()
    hero: Hero;

    constructor(
        private heroService: HeroService,
        private route: ActivatedRoute,
        private location: Location,
        private titleService: Title
    ) { }

    public ngOnInit(): void {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];

            this.heroService.getHero(id)
                .then(hero => this.hero = hero)
                .then(function () { this.setTitle(this.hero.name); }); // this is the line I have added
        });
    }

    public save(): void {
        this.heroService.update(this.hero)
            .then(() => this.goBack());
    }

    public delete(): void {
        this.heroService
            .delete(this.hero.id)
            .then(() => this.goBack());
    }

    public goBack(): void { 
        console.log('back')
        this.location.back();
    }

    private setTitle(newTitle: string) {
        this.titleService.setTitle(newTitle);
    }
}

从我的代码中可以看出,我试图在设置英雄已经运行的承诺之后设置标题。但是,似乎没有任何事情发生 - 没有抛出错误,标题也没有改变。

我在这里做错了什么?我不会这样承诺吗?

1 个答案:

答案 0 :(得分:2)

更改

.then(function () { this.setTitle(this.hero.name); });

.then(() => { this.setTitle(this.hero.name); }); 

保留this

的范围

另见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions