简体   繁体   English

无法设置 BehaviorSubject 的订阅数据

[英]Unable to set subscribe data of BehaviorSubject

Trying with BehaviorSubject and 2 components.尝试使用 BehaviorSubject 和 2 个组件。 But not able to set the data receiving from subscribe.但无法设置从订阅接收的数据。

Components A组件 A

name:string = 'Test';
  constructor( private data: DataService) { }
  ngOnInit() {
    this.data.currentMessage.subscribe(val => this.name = val);
  }

Component B (with text field)组件 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);
  }

on form submit setData() function is called.在表单上提交 setData() 函数被调用。

Data Service数据服务

private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();
  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

On load:负载:

在此处输入图片说明

On Submit form:在提交表单上:

在此处输入图片说明

Value is changing in Component B but not in A. Whats wrong in A that its not changing?组件 B 中的值正在改变,但 A 中的值没有改变。 A 中的值没有改变有什么问题? Please Help.请帮忙。

Your service is not a singleton service.您的服务不是单例服务。 You have to provided it at the module level or at the root level to make it a shared service or a singleton service.您必须在模块级别或根级别提供它以使其成为共享服务或单例服务。

Providing service at the component level will create a new instance which is available only to that component.在组件级别提供服务将创建一个仅可用于该组件的新实例。

You can provide the service at the root level in the following way or from the providers array within the module file.您可以通过以下方式或从模块文件中的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)
  }

}

Also remove providers array from component A and B files, since we are providing at the root level同时从组件 A 和 B 文件中删除 providers 数组,因为我们在根级别提供

Comp A比较A

@Component({
  selector: 'app-comp-a',
  templateUrl: './comp-a.component.html',
  styleUrls: ['./comp-a.component.css'],
  // providers: [DataService]
})

Comp B比较 B

@Component({
  selector: 'app-comp-b',
  templateUrl: './comp-b.component.html',
  styleUrls: ['./comp-b.component.css'],
  // providers: [DataService]
})

Forked Demo 分叉演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM