簡體   English   中英

帶有{{responseType:'text}}的角度http.get錯誤

[英]Angular http.get error with {{responseType: 'text}}

每當我在http.get(url)調用中嘗試使用{{requestType:'text'}}時,都會收到一個錯誤,我無法進行區分,並且只允許使用數組和可迭代對象。 但是,我正在拿我的對象並將其轉換為數組。 我需要一些幫助來了解我的錯誤以及如何解決我的情況

當我刪除RequestType時,數組不會出現任何問題,並顯示在前端。

----service-----

 getAll(){
    const requestOptions: Object = {
      /* other options here */
      responseType: 'text'
    }
    return this.http.get<any>(this.url, requestOptions);
} 

---component .ts----- 

notificationsFass: any[];

  constructor(route: ActivatedRoute, private metaService: Meta, private notificationService: NotificationsFassService) {
    this.notificationsFass = [];
}


ngOnInit() {
    this.notificationService.getAll()
      .subscribe(notificationsFass => {
        this.notificationsFass = notificationsFass;
      }
        );
}

---html---

<div *ngFor="let m of notificationsFass">

---error----
ERROR Error: Error trying to diff '[{"incidentNumber":700,"createdByName":"FASS Notification","createdDate":"2019-03-27T09:18:15.000+0000"}]'. Only arrays and iterables are allowed

根據錯誤消息中的json,您需要執行以下操作:

  • 定義一個接口,我使用了名稱INotification 這將定義反序列化json響應上可用的成員。
  • 強烈鍵入方法的返回類型,並在http.get<T>提供泛型類型參數。 調用http.get ,它將嘗試反序列化從服務器到對象圖的json響應。 通過將INotification[]定義為返回類型,其他調用者(例如來自組件)現在可以安全地調用返回類型上的成員,例如find或其他Array.prototype成員,以及訪問數組實例中定義的成員。

responseType: 'text'僅當您不從服務器發出響應響應為text而不是json時才需要responseType: 'text' 前者可以用發生postputdelete通話所在服務器可能只在發送響應狀態,並沒有消息體。

這是根據上述反饋重寫的服務代碼。

notificationsFassService.ts

export interface INotification {
    incidentNumber: number;
    createdByName: string;
    createdDate: string;
}

export class NotificationsFassService {
    constructor (private readonly http: HttpClient) { }

    getAll():Observable<INotification[]> {
        return this.http.get<INotification[]>(this.url);
    } 
}

notificationsFassComponent.ts

export class NotificationsFassComponent implements OnInit {
    notificationsFass: INotification[];

    constructor(route: ActivatedRoute, private metaService: Meta, private notificationService: NotificationsFassService) {
        this.notificationsFass = [];
    }

    ngOnInit() {
        this.notificationService.getAll()
          .subscribe(notificationsFass => {
             this.notificationsFass = notificationsFass;
          });
    }
}

暫無
暫無

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

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