如何使用RxJS BehaviorSubject在组件之间而不是字符串之间传递数字

时间:2019-05-06 09:09:45

标签: angular rxjs

我正在关注本教程:

  

https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/#sibling-component-ts

尝试在两个组件之间传递数字。
在学习完该教程之后,我仅设法在组件之间传递字符串。

  

这是parent-of-sibling.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
  selector: 'app-parent-of-sibling',
  template: `
  <br>
  Here's the received message from sibling
  <br>

  {{message}}
  <br>

`,  styleUrls: ['./parent-of-sibling.component.css']
})
export class ParentOfSiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}
  

这是sibling.component.ts:

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-sibling',
  template: `
  <button (click)="newMessage()">Send message to parent</button>
`,  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
  }

  newMessage() {
    this.data.changeMessage("MESSAGE RECEIVED FROM SIBLING")
  }

}
  

最后是data.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

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

  constructor() { }

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

}

如果我要传递字符串,这将非常有效:
enter image description here enter image description here
当我尝试使用相同的代码传达电话号码时,应用程序显示错误。
所以这是我的问题:
1 /是什么原因导致错误? (即:我确实知道此代码适用于字符串,而不适用于数字,但为什么它仅适用于字符串?)
2 /有什么办法可以解决这个问题?
谢谢!

1 个答案:

答案 0 :(得分:0)

感谢@Buczkowski的技巧,我解决了这个问题。

export class DataService {
  private messageSource = new BehaviorSubject<Number>(4);
  currentMessage = this.messageSource.asObservable();
  constructor() { }
  changeMessage(message: Number) {
    this.messageSource.next(message);
  }
}