从其他组件访问模板中的变量

时间:2016-01-17 20:06:04

标签: angular

我需要帮助在其他组件中设置模板中的变量。

例如:

AppComponent

@Component({
    selector: 'app',
    templateUrl: '/templates/layout',
    directives: [ROUTER_DIRECTIVES, RouterLink]
})

export class AppComponent {

    currentShop:Shop;

    constructor(router: Router, shopProvider:ShopProvider){
        shopProvider
            .getCurrentShop()
            .toPromise()
            .then((response) => {
                router.navigate(['/System']);
            });
    }
}

模板:

<app>
    <div>{{currentShop.name}}</div>
</app>

商店:

export class Shop{

    private _id;

    private _name;

    constructor(id:number, name:string) {
        this._id = id;
        this._name = name;
    }

    get id() {
        return this._id;
    }

    get name() {
        return this._name;
    }
}

SystemComponent:

@Component({
    template: '',
    directives: [RouterOutlet]
})

export class SystemComponent{

    private _routeParams:RouteParams;

    private _shopProvider:ShopProvider;

    currentShop:Shop;

    constructor(routeParams:RouteParams,shopProvider:ShopProvider){
        this._routeParams = routeParams;
        this.currentShop = new Shop(1, 'Test');
    }

}

运行应用程序后,我收到此错误:

[Error] EXCEPTION: TypeError: undefined is not an object (evaluating 'l_currentShop0.name') in [{{currentShop.name}} in AppComponent@22:12]

如果我尝试直接从AppComponent设置currentShop,则没有问题。从SystemComponent它不起作用。

1 个答案:

答案 0 :(得分:0)

我不知道ShopProvider是否异步提供了当前的电流。如果是这样,也许你会尝试显示它,而它不在那里。

也许Elvis运营商可以帮助您:

{{currentShop?.name}}

没有任何其他提示(关于ShopProvider服务如何运作以及如何在视图中显示currentShop属性的一些想法),很难为您提供更多帮助。

亨利