2017-07-31 51 views
4

以下Google's official Angular 4.3.2 doc here,我能夠做一個簡單的get請求從本地json文件。我想練習從JSON佔位符站點打到真正的端點,但我很難找出要在運算符中放置什麼。我製作了一個IUser接口來捕獲有效負載的字段,但帶有.subscribe(data => {this.users = data})的行會引發錯誤Type 'Object' is not assignable to type 'IUser[]'。處理這個問題的正確方法是什麼?看起來很基本,但我是一個菜鳥。「類型'對象'是不可分配類型」與新的HttpClient/HttpGetModule

我的代碼如下:

import { Component, OnInit } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 
import { IUsers } from './users'; 

@Component({ 
    selector: 'pm-http', 
    templateUrl: './http.component.html', 
    styleUrls: ['./http.component.css'] 
}) 
export class HttpComponent implements OnInit { 
    productUrl = 'https://jsonplaceholder.typicode.com/users'; 
    users: IUsers[]; 
    constructor(private _http: HttpClient) { } 

    ngOnInit(): void {  
    this._http.get(this.productUrl).subscribe(data => {this.users = data}); 
    } 

} 
+1

由於數據具有不類型IUsers,試試這個'.subscribe((數據:IUsers)= > ...''或'this.users = data as any;' – cyrix

+0

謝謝@cyrix。'data as any'在我的情況中取得了訣竅 – negrotico19

回答

8

實際上,你有幾個選擇這裏,但使用泛型丟給你期待的類型。

http.get<IUsers[]>(this.productUrl).subscribe(data => ... 

    // or in the subscribe 
    .subscribe((data: IUsers[]) => ... 

而且我建議你的模板,自動訂閱/退訂,特別是如果你不需要任何花哨的邏輯使用異步管道,你只是映射值。

users: Observable<IUsers[]>; // different type now 

this.users = this.http.get<IUsers[]>(this.productUrl); 

// template: 
*ngFor="let user of users | async" 
+1

謝謝,鑄造工作很棒! – midnightnoir

8

我對角文檔團隊和一個開放的待辦事項是改變這些文檔顯示了「最佳實踐」的方式來訪問HTTP ...這是通過服務。

下面是一個例子:

import { Injectable } from '@angular/core'; 
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/throw'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/map'; 

import { IProduct } from './product'; 

@Injectable() 
export class ProductService { 
    private _productUrl = './api/products/products.json'; 

    constructor(private _http: HttpClient) { } 

    getProducts(): Observable<IProduct[]> { 
     return this._http.get<IProduct[]>(this._productUrl) 
      .do(data => console.log('All: ' + JSON.stringify(data))) 
      .catch(this.handleError); 
    } 

    private handleError(err: HttpErrorResponse) { 
     // in a real world app, we may send the server to some remote logging infrastructure 
     // instead of just logging it to the console 
     let errorMessage = ''; 
     if (err.error instanceof Error) { 
      // A client-side or network error occurred. Handle it accordingly. 
      errorMessage = `An error occurred: ${err.error.message}`; 
     } else { 
      // The backend returned an unsuccessful response code. 
      // The response body may contain clues as to what went wrong, 
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`; 
     } 
     console.error(errorMessage); 
     return Observable.throw(errorMessage); 
    } 
} 

然後,組件是這樣的:

ngOnInit(): void { 
    this._productService.getProducts() 
      .subscribe(products => this.products = products, 
         error => this.errorMessage = <any>error); 
} 
+0

剛剛開始你的課程!將我的代碼重構爲服務以遵循最佳實踐! – midnightnoir

+0

太棒了!本課程目前使用舊的Http服務。我們現在正在進行更新。 – DeborahK

+0

羅傑說,我試圖找出自己作爲一個練習:P – midnightnoir

相關問題