【发布时间】:2020-01-17 17:13:26
【问题描述】:
我有两个组件和一个服务。 HomeComponent 是父组件,ContactComponent 是子组件,它有一个数组,其中包含两个联系人的两个元素。
但是,我有一个我想使用的 observable,我想存储 ContactComponent 返回的数据,并将它们放在 Home Component 的两个变量中。
这是我的代码:
服务
export class AppDataService {
constructor() { }
private data = new BehaviorSubject<string>("Home");
//this is what your components subsribes to
currentData() : Observable<string> {
return this.data.asObservable();
}
//this function allows you to change the value to be accessed by other components
changeData(message: string) {
this.data.next(message);
}
}
ContactComponent.ts
public contactsChanged = new Subject();
public updatedContact:any;
constructor(private contacts: Contacts, private storage: Storage, private appData : AppDataService) {
this.getContact();
}
key = 'contacts';
mContacts = [
{
id: 0,
name: '',
number: ''
},
{
id: 1,
name : '',
number: ''
}
];
pickContact(contactId) {
this.appData.currentData().subscribe((message:string) => this.updatedContact = message);
this.mContacts[contactId].name = "Mitchell";
this.mContacts[contactId].number = (Math.random() * 0.5).toString();
this.appData.changeData(this.mContacts[0].number);
this.appData.changeData(this.mContacts[1].number);
console.log("contactsChanged: " + this.mContacts[0].number);
console.log("contactsChanged: " + this.mContacts[1].number);
}
HomeComponent.ts
this.appData.currentData().subscribe((message:string) => {
//here i log changes detected on the console
console.log("i have changed " + message);
//you can perform any call or action here e.g
//update a variable
this.numberOne = message;
this.numberTwo = message;
//or call a function
this.canCall();
});
我想将第一个元素的数字存储在 numberOne 中,将第二个数字存储在 NumberTwo 中。但是显然这存储了相同的数字。
【问题讨论】:
-
如果您想发送 pairs 值,请将其更改为
Observable<[string, string]>。 -
能否说的更具体一些
-
好吧,目前你已经围绕
Observable<string>构建了所有东西,它一次发送一个值。现在你说你想处理 pairs 的值。所以发送tuple,Observable<[string, string]>,然后你会同时得到这两个值。
标签: angular typescript rxjs