【发布时间】:2017-02-04 23:22:05
【问题描述】:
我可以从另一个组件更改组件变量的值,如本例中的console.log() 所示。
我的问题是第二个组件的视图没有刷新,尽管变量发生了变化。
例子:
first.component.ts
import {Component} from '@angular/core';
import {SecondComponent} from './second.component';
@Component({
selector: 'first',
template: `
<h2>First component</h2>
<button (click)="changeOutside()">Change</button>
`,
providers: [SecondComponent]
})
export class FirstComponent {
constructor(private otherComponent: SecondComponent) {}
changeOutside() {
this.otherComponent.change();
}
}
second.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'second',
template: `
<h2>Second component</h2>
<div>Pet: {{animal}}</div>
<button (click)="change()">Change</button>
`
})
export class SecondComponent {
animal: string = 'Dog';
change() {
this.animal = 'Cat';
console.log(this.animal);
}
}
这两个组件完全不相关来自 DOM 树的不同分支。
我也试过第一个组件发出一个事件,第二个组件订阅它,结果相同,变量改变但视图没有更新。
Günter's suggestion(谢谢)之后,我尝试了下一个解决方案,但没有成功。即使console.log 也不起作用。
first.component.ts
import {Component} from '@angular/core';
import {UpdateService} from './update.service';
@Component({
selector: 'first',
template: `
<h2>First component</h2>
<button (click)="changeOutside()">Change</button>
`
})
export class FirstComponent {
constructor(private updateService: UpdateService) {}
changeOutside() {
this.updateService.changeAnimal('Cat');
}
}
update.service.ts
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UpdateService {
// Observable string sources
private newAnimalSource = new Subject<string>();
// Observable string streams
newAnimal$ = this.newAnimalSource.asObservable();
changeAnimal(animal: string) {
this.newAnimalSource.next(animal);
}
}
second.component.ts
import {Component} from '@angular/core';
import {UpdateService} from './update.service';
import {Subscription} from 'rxjs/Subscription';
import {Subject} from 'rxjs/Subject';
@Component({
selector: 'second',
template: `
<h2>Second component</h2>
<div>Pet: {{animal}}</div>
<button (click)="change()">Change</button>
`
})
export class SecondComponent {
animal: string = 'Dog';
subscription: Subscription;
constructor(private updateService: UpdateService) {
this.subscription = updateService.newAnimal$.subscribe(
animal => {
console.log(animal);
this.animal = animal;
});
}
change() {
this.animal = 'Cat';
}
}
已解决
最后,Günter 提出的解决方案在app.module.ts 的@NgModule 中添加UpdateService 作为provider 后奏效了
【问题讨论】:
标签: angular components