[英]*ngIf async pipe angular merge with another observable
請給我一些關於我的應用程序的解決方法的想法! 我試圖在我的組件中動態切換模板,但有奇怪的行為。 謝謝! 這是stackblitz
基本上我想要的是:我想從我的警報組件中的服務接收異步數據(節點),並在我的#initTemplate中顯示此數據(節點),然后我想獲取此數據的id(節點),用此發送請求id並獲取我希望在#stylesTemplate中顯示的其他數據(樣式)。 兩個模板都在我的警報組件中。
我的問題是什么? 我意識到我的組件需要的行為,但這不是我需要的......我在做什么:1。點擊“pushData”按鈕2.查看我的警報組件3.單擊更改模板按鈕(!!組件消失!!) 4。再次單擊“pushData”5。使用更改的模板查看我的組件
我需要切換組件的模板而不會消失。
這是我的簡化警報組件(另見stackblitz工作示例)
class AlertComponent implements OnInit, OnDestroy {
private subscription: Subscription;
message: any;
node$: Observable<{}>;
styles$: Observable<{}>;
constructor(private dataService: DataService) { }
activeInit: boolean = true;
ngOnInit() {
this.node$ = this.dataService.getAsyncData().pipe(share());
this.styles$ = this.node$.pipe(
mergeMap(node => {
if(!!node) {
// I need node here, because getSecondAsyncData send request with this data
return this.dataService.getSecondAsyncData(node);
}
else return of(null);
}));
}
ngOnDestroy() {
}
openSecond() {
this.activeInit = false;
}
openFirst() {
this.activeInit = true;
}
close() {
this.dataService.sendNodeToSubscribe(null);
}
這是我的html與兩個模板:
<ng-container *ngTemplateOutlet="activeInit ? initTemplate : stylesTemplate"></ng-container>
<ng-template #initTemplate>
<div class="card left-settings position-fixed" *ngIf="(node$ | async) as node;">
<div class="row justify-content-end mx-0">
<div class="col-0">
<button type="button" class="btn btn-block btn-ghost-light p-1 px-2" (click)="close()">Close</button>
</div>
</div>
<div class="row custom-width">
<div class="col-lg-12">
<button (click)="openSecond()">switch second template</button>
</div>
</div>
</div>
</ng-template>
<ng-template #stylesTemplate>
<div class="card left-settings position-fixed" *ngIf="(styles$ | async) as styles;">
<div class="row justify-content-end mx-0">
<div class="col-0">
<button type="button" class="btn btn-block btn-ghost-light p-1 px-2" (click)="close()">
Close
</button>
</div>
</div>
<div class="row custom-width">
<label>{{styles.isIcon}}</label>
<label>{{styles.radius}}</label>
<button (click)="openFirst()">switch first template</button>
</div>
</div>
</ng-template>
謝謝 !!
你只需要替換下面的代碼,
使用BehaviorSubject :BehaviorSubject包含一個值。 訂閱時,它會立即發出值。 主題沒有值。
private subject = new Subject<any>();
同
private subject = new BehaviorSubject(new String());
這里是Stackblitz的更新
更新!!
謝謝!! 不錯的建議,這工作正常,但我需要在收到真實數據之前隱藏我的組件。 為此,我修改了你的解決方案,現在我用它:
private subject = new BehaviorSubject(null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.