当服务中声明的变量更改时,我正在尝试更新组件中声明的变量。我正在使用主题。然而,什么都没有发生。
应用程序。单元ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ShareDataService } from './share-data.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ShareDataService],
bootstrap: [AppComponent]
})
export class AppModule { }
应用程序。组成部分ts
import { Component } from '@angular/core';
import { ShareDataService } from './share-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
_subscription;
constructor(private shareDataService:ShareDataService)
{
//this.title=this.shareDataService.title;
this._subscription = shareDataService.titleChange.subscribe((value) => {
this.title = value;
//alert(this.title);
console.log("COmponent::::::::::::::"+this.title);
});
}
}
shareDataService。ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ShareDataService {
title:string="TITLE";
titleChange: Subject<string> = new Subject<string>();
constructor() {
setTimeout(
function()
{
this.title="BACDEF";
//console.log(this.title);
this.titleChange.next(this.title);
}
,1000);
}
}
对于服务中定义的主题,它会给出一个错误消息“无法读取未定义的属性‘next’”。实现这一点最合适的方式是什么?