尝试使用BehaviorSubject和2个组件。但无法设置从订阅接收的数据。
组件A
name:string = 'Test';
constructor( private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(val => this.name = val);
}
组件B (带有文本字段)
name:string = 'Test';
frm:FormGroup;
constructor(private fb: FormBuilder, private data: DataService) { }
ngOnInit() {
this.setup();
this.data.currentMessage.subscribe(val => this.name = val);
}
setup(){
this.frm = this.fb.group({
name:['']
});
}
setData(){
this.data.changeMessage(this.frm.get('name').value);
}
在表单Submit setData()函数上被调用。
数据服务
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
正在加载:
在提交表单上:
值在B组件中发生变化,但在A组件中没有发生变化。请帮忙。
答案 0 :(得分:0)
您的服务不是单人服务。您必须提供 在模块级别或根级别将其共享 服务或单个服务。
在组件级别提供服务将创建一个新实例 仅适用于该组件。
您可以通过以下方式或通过 module 文件中的 providers 数组在根级别提供服务。
data.service
@Injectable({
providedIn: 'root'
})
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
也从组件A和B文件中删除提供者数组,因为我们是在根级别提供的
比较A
@Component({
selector: 'app-comp-a',
templateUrl: './comp-a.component.html',
styleUrls: ['./comp-a.component.css'],
// providers: [DataService]
})
比较B
@Component({
selector: 'app-comp-b',
templateUrl: './comp-b.component.html',
styleUrls: ['./comp-b.component.css'],
// providers: [DataService]
})