簡體   English   中英

無法通過 Angular 中的 ngOnInit 通過 Observable 從 http.get 獲取數據

[英]Unable to get data from http.get via Observable via ngOnInit in Angular

在我的組件初始化中,我從服務器獲取數據

 import {Rules} from "../../interfaces/interfaces";
 rules: Rules
 ngOnInit() {
  this.tt = this.rulesService.getUserClientRules().subscribe(
   t => {
     console.log(t)
     console.log(t.clientRules.canAll)
     this.rules = t.clientRules
   },
   error => {
    console.log(error.error.message)
   }
  )
 }

我的服務代碼是

getUserClientRules(): Observable<Rules> {
return this.http.get<Rules>('/api/rules/getClientUserRules/')}

and I have interface like:

export interface Rules {
 clientRules: any
}

我得到這樣的回應:

**{clientRules: {canAll: true, canSee: false}}**

如何將此對象推送到我的規則對象中? 我想像rules.canAllrules.canSeeAll一樣使用它...

當我嘗試console.log(this.rules)我變得未定義

我需要這個結構規則{ canAll: true, canSee: true }我需要用它來檢查 * ngIf="rules.canSee"

謝謝您的反饋!!!

根據您的要求,界面實際上應該看起來像

export interface Rules {
  canAll: boolean;
  canSee: boolean;
}

然后你可以 RxJS map運算符從 HTTP 調用返回clientRules屬性

服務

getUserClientRules(): Observable<Rules> {
  return this.http.get<Rules>('/api/rules/getClientUserRules/').pipe(
    map(response => response['clientRules'])
  );
}

然后,您可以將響應直接分配給組件中的rules變量

成分

rules: Rules

ngOnInit() {
  this.tt = this.rulesService.getUserClientRules().subscribe(
    t => {
      console.log(t);
      console.log(t.canAll);
      this.rules = t; // <-- the response is already the `clientRules` property
    },
    error => {
      console.log(error.error.message)
    }
  );
}

然后,您可以使用安全導航操作符?.在模板中使用它?. 避免不必要的undefined錯誤。

模板

<div *ngIf="rules?.canSee">
  User can see...
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM