我无法想象为什么或如何从回调中更新值,我虽然BehaviorSubject只能通过next()更新...但也许是缺乏睡眠?
这是代码:
import { Component, OnInit, Input, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private testSource = new BehaviorSubject([]);
testCurrent = this.testSource.asObservable();
constructor() { }
changeTest(test: any) {
this.testSource.next(test);
}
}
@Component({
selector: 'app-another',
template: `<div *ngFor="let nope of whatEver">{{nope.bananas}}</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class AnotherComponent {
@Input() rando: string;
constructor(private data: DataService) { }
whatEver: [];
ngOnInit() {
this.data.testCurrent.subscribe(aha => {
// WORKS FINE:
const omg = JSON.parse(JSON.stringify(aha))
this.whatEver = omg.reduce((accu, a) => {
// DOES NOT WORK (changes the variable aha -> WHY?):
//this.whatEver = aha.reduce((accu, a) => {
a.bananas = a.bananas.filter(b => b === this.rando || b === "yellow");
accu.push(a);
return accu;
}, []);
});
}
}
@Component({
selector: 'my-app',
template: `<app-another *ngFor="let why of maybe" [rando]="why"></app-another>`,
styles: [`h1 { font-family: Lato; }`]
})
export class AppComponent implements OnInit {
idontknow = [
{
id: "come-on",
bananas: ["yellow", "big", "tasty"]
}
];
maybe = ["yellow", "big", "tasty"];
constructor(private data: DataService) { }
ngOnInit() {
this.data.changeTest(this.idontknow);
}
}
这是工作stackblitz:https://stackblitz.com/edit/angular-hdez5o
我的问题:由于代码在上面,它工作正常(我有我的香蕉)。但是,如果你注释掉WORKS FINE
and下方的2行,则取消注释DOES NOT WORK
下面的行,那么我只有黄色的香蕉。即使在组件的不同实例中,它是否可以成为aha对象的有趣引用?怎么可能,我错过了什么?我是否必须复制aha才能使用?我很困惑。
原因是因为这一行:
a.bananas = a.bananas.filter(...);
您正在重新分配BehaviorSubject发出的对象的属性。它发出三次(每个应用程序一次 - 另一个订阅它)。这意味着第二次,a.bananas
将是从先前订阅过滤的任何内容。
要解决此问题,请不要重新分配对象属性。创建具有相应属性的新对象。例如:https://stackblitz.com/edit/angular-tumnrd?file=src/app/app.component.ts
const bananas = a.bananas.filter(...);
accu.push({ ...a, bananas });
您也不需要(或必然要)创建订阅。您必须取消订阅(可能在ngOnDestroy中)或存在内存泄漏的可能性。我建议使用异步管道来处理:https://stackblitz.com/edit/angular-tumnrd?file=src/app/app.component.ts
this.whatEver = this.data.testCurrent.pipe(
map(aha =>
aha.map(({ bananas }) => ({
bananas: bananas.filter(b => b === this.rando || b === 'yellow')
}))
)
);
// ... in template ...
<div *ngFor="let nope of whatEver | async">{{nope.bananas}}</div>