【问题标题】:Set title after angular promise在角度承诺之后设置标题
【发布时间】:2016-10-10 20:03:06
【问题描述】:

我正在尝试学习 Angular,所以我刚刚完成了 heroes tutorial

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

这在我的仪表板页面上运行良好,我可以简单地在 on init 中调用标题服务,所以我想我会尝试将它添加到我的英雄详细信息页面,看看我是否可以让文档标题成为英雄名称:

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

从我的代码中可以看出,我试图在设置英雄的承诺运行后设置标题。然而,似乎什么都没有发生 - 没有抛出错误,标题也没有改变。

我在这里做错了什么?我会不会那样把承诺锁起来?

【问题讨论】:

    标签: angular angular-promise


    【解决方案1】:

    改变

    .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

    【讨论】:

    • 哇,知道了就这么简单!当它允许我时会接受答案
    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2015-11-22
    • 2016-08-31
    相关资源
    最近更新 更多