Stackblitz 举例说明如何通过服务在组件之间应用可观察和 @Input 数据更改。
您将需要一个服务和带有订阅的 Rxjs 来以有角度的方式进行操作:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UserNameService {
execChange: Subject<any> = new Subject<any>();
constructor() {}
/**
* Use to change user name
* @data type: string
*/
userNameChange(data: string) {
this.execChange.next(data);
}
}
然后在您希望更改用户名的每个组件中添加订阅:
constructor(private userNameService : UserNameService) {
this._subscription_user_name = this.userNameService.execChange.subscribe((value) => {
this.userName= value; // this.username will hold your value and modify it every time it changes
});
}
如何更改值,以便每个订阅都可以修改值?在您的服务中调用您的 execChange 函数:
this.userNameService.userNameChange('Thor');
编辑:@Vikas 的评论是正确的,而且非常不言自明...您需要将服务添加到 ngModule 提供程序数组,否则您会因未知的提供程序错误而头疼。
@NgModule({
imports: [
...
],
declarations: [...],
providers: [UserNameService]
})
如果您需要跨选项卡或刷新页面时保留数据,也请使用localstorage。