根据组件

时间:2017-09-25 10:00:01

标签: angular

在app.component.html中,我有以下代码:

<nav class="navbar navbar-default">
<div class="container-fluid">
    <div class="navbar-header">
        <a class="navbar-brand" href="/viewAll">Birthday Manager</a>
    </div>
    <div class="nav navbar-nav navbar-right">
        <span>{{ headerText }}</span>
    </div>
</div>

我创建了由3个组件共享的服务,该服务具有“headerText”属性。

在我的app.component.ts文件中,我这样做了:

headerText = this.sharedService.headerText;

现在,在我的一个组件中,我已经这样做了:

ngOnInit() {
    this.sharedService.headerText = 'Create Employee';
}

但是,仍然没有更新headerText绑定。

怎么做?

2 个答案:

答案 0 :(得分:1)

app.component.ts

import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

sharedService: any = {};

constructor() { }

 ngOnInit() {
    this.sharedService.headerText = 'Create Employee';
}
}

app.component.html

<span>{{sharedService.headerText}}</span>

答案 1 :(得分:0)

我猜你错误的两种方法来解决你的问题...最简单的方法是在你的HTML代码中使用对服务的引用:

<div class="nav navbar-nav navbar-right">
    <span>{{ sharedService.headerText }}</span>
</div>

如果参与服务是公开的。

但是最好的解决方案(我想你想用它)是使用Observables对象。这是一个很长的主题(您可以阅读它here),但您可以在组件中声明一次变量,并跟踪其中的所有更改。

简而言之:您必须在服务title: Observable<string>中声明Observable对象,如果您在某个组件headerTitle$: Observable<string> = this.sharedService.title;中传递对observable的引用,您将跟踪你的html组件(使用异步管道)以这种方式<span>{{ headerTitle$ | async }}</span>

那是你的意思吗?如果我能解释一下,请告诉我。