在 Angular 11 應用程式中,我有一個簡單的服務,可以創建get請求并讀取 JSON。
服務:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Promo } from '../models/promo';
@Injectable({
providedIn: 'root'
})
export class PromoService {
public apiURL: string;
constructor(private http: HttpClient) {
this.apiURL = `https://api.url.com/`;
}
public getPromoData(){
return this.http.get<Promo>(`${this.apiURL}/promo`);
}
}
在組件中,我需要將產品陣列與活動產品陣列(包含在上面提到的 JSON 中)進行比較,并突出顯示促銷產品:
export class ProductCardComponent extends DestroyableComponent implements OnInit, OnChanges
{
public promoData: any;
public promoProducts: any;
public isPromoProduct: boolean = false;
public ngOnInit() {
this.getCampaignData();
}
public ngOnChanges(changes: SimpleChanges): void {
this.getCampaignData();
}
public getPromoData() {
this.promoService.getPromoData().pipe(takeUntil(this.destroyed$)).subscribe(data => {
this.promoData = data;
this.promoProducts = this.promoData.products;
let promoProduct = this.promoProducts.find((product:any) => {
return this.product.unique_identifier == product.unique_identifier;
});
if (promoProduct) {
// Update boolean
this.isPromoProduct = true;
}
});
}
}
在組件的 html 檔案(模板)中,我有:
<span *ngIf="isPromoProduct" class="promo">Promo</span>
沒有編譯錯誤。
問題
由于我一直無法理解的原因isPromoProduct,盡管我在ngOnInit and ngOnChanges中呼叫了函式,但模板不會對變數的更改做出反應,并且模板也不會更新。
問題:
- 我的錯誤在哪里?
- 更新模板的可靠方法是什么?
uj5u.com熱心網友回復:
subscribing對于Observable內部.ts檔案,這通常不是最佳做法。嘗試通過使用async pipeof來避免它Angular。
您需要將 observable 存盤在變數中,而不是從 observable 回傳的資料,例如:
// this variable holds the `observable` itself.
this.promoData$ = this.promoService.getPromoData()
然后在模板中你可以這樣做:
<div *ngIf="promoData$ | async as promoData">
here you can access the promoData
</div>
您仍然可以使用pipe()映射資料等,但避免subscribe()
uj5u.com熱心網友回復:
isPromoProduct布林值不是輸入。用裝飾器裝飾的屬性的ngOnChanges更改會觸發@Input。對于您的特定情況,您可以手動注入ChangeDetectorRef并觸發更改檢測:
constructor(private cdr: ChangeDetectorRef) {}
// ...
public getPromoData() {
this.promoService.getPromoData().subscribe(data => {
// ...
if (promoProduct) {
// Update boolean
this.isPromoProduct = true;
this.cdr.detectChanges();
}
});
}
您也不需要管理httpClient訂閱。一個簡單的getorpost請求生成的 observables 將在它們發出請求的回應后完成。您只需要顯式管理熱可觀察物件的取消訂閱(您從您自己實體化的主題創建)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529099.html
