[英]ASYNC pipe not working on BehaviorSubject
I'm trying to use Async pipe but when i trigger some new data to my BehaviorSubject, the value is not even fetch by the subject.我正在尝试使用 Async pipe 但是当我触发一些新数据到我的 BehaviorSubject 时,主题甚至没有获取该值。 If i change the async pipe by a manualy subscription, i receive the value but the view still not updated.如果我通过手动订阅更改异步 pipe,我会收到该值,但视图仍未更新。 I have to use manualy detectChange for this case.对于这种情况,我必须使用手动检测更改。
Services:服务:
@Injectable({
providedIn: 'root',
})
export class WalletService {
ethereum: any;
currentAccountSubject: BehaviorSubject<any> = new BehaviorSubject([]);
currentNetworkSubject: BehaviorSubject<any> = new BehaviorSubject(null);
currentProviderSubject: BehaviorSubject<any> = new BehaviorSubject(null);
constructor() {
this.ethereum = (<any>window).ethereum;
this.checkWalletConnected().subscribe();
this.accountChanged();
this.networkChanged();
}
private accountChanged(): void {
this.ethereum.on('accountsChanged', (accounts: string[]) => {
if(accounts.length === 0) this.currentProviderSubject.next(null);
console.log('accountChanged', accounts) //WORKING FINE
this.currentAccountSubject.next(accounts);
});
}
}
Components:成分:
export class AppComponent implements OnInit{
accounts$: Observable<string[]> = of([]);
constructor(private walletService: WalletService) {}
ngOnInit(): void {
this.accounts$ = this.walletService.currentAccountSubject.pipe(
skip(1),
distinctUntilChanged((prev, curr) => prev[0] === curr[0]),
tap(wallets => console.log('wallets', wallets)), //NOT WORKING WITH ASYNC PIPE BUT WORKING WHITOUT
)
}
}
HTLM: AppComponent: HTLM:应用组件:
<app-toolbar [accounts]="accounts$ | async"></app-toolbar>
ToolBarComponent:工具栏组件:
<mat-toolbar>
<span>
<img src="/assets/mySvg.svg" alt="svg" />
</span>
<span class="spacer"></span>
<ng-container *ngIf="accounts && accounts.length > 0; else btnConnect">{{accounts[0]}}</ng-container>
<ng-template #btnConnect>
<button mat-raised-button color="primary" (click)="connectToWallet()">Connect Wallet</button>
</ng-template>
</mat-toolbar>
If you want to try yourself: https://stackblitz.com/edit/angular-xkrt7c?file=src/app/app.module.ts如果您想自己尝试: https://stackblitz.com/edit/angular-xkrt7c?file=src/app/app.module.ts
The below line is the problem, ensure that unique value is being compared inside the distinctUntilUnchanged
.下一行是问题所在,请确保在distinctUntilUnchanged
内比较唯一值。
distinctUntilChanged((prev, curr) => prev[0] === curr[0]), // <- problem here
You can try to fix it yourself if not please share a sample data for prev
and curr
inorder to resolve this issue and also provide the unique key inside accounts!如果没有,您可以尝试自己修复它请分享prev
和curr
的示例数据以解决此问题并提供帐户内的唯一密钥!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.