0

我收到來自http服務的響應對象,角度爲2,如果我嘗試控制檯response.prop,它不工作,它顯示以下錯誤:dot(例如.reponse.title)屬性無法處理從角度2中的http服務獲得的響應對象

D:/ABC/angular-training/angular_cli/src/app/shared/footer/footer.component.ts (16,28): Property 'prop' does not exist on type '{}'.)

但是當我做響應[「託」]然後我得到我的價值。

這裏是我的代碼:

export class FooterComponent { 
    constructor(private httpService : HttpService) { 
    this.httpService.getData("http://127.0.0.1:8887/footer.json").then(response => { 
     console.log(response);//shows object 
     console.log(response.prop);//not works 
     console.log(response["prop"]);//works fine 
    }); 
    } 
} 

這裏是我的HTTPService代碼:

export class HttpService { 
private Title = URL;// URL to web api 

constructor(private http: Http) { } 

getData(url="this.Title"): Promise<{}> { 
return this.http.get(url) 
      .toPromise() 
      .then(response => 
      response.json() 
      ) 
      .catch(this.handleError); 
} 

private handleError(error: any): Promise<any> { 
console.error('An error occurred', error); 
return Promise.reject(error.message || error); 
} 
} 

而且這是從服務器的JSON響應:

{ 
"footerLinks" : { 
    "social":[{ 
    "text":"Google", 
    "link":"www.google.com" 
    }, 
    { 
    "text":"Facebook", 
    "link":"www.facebook.com" 
    }, 
    { 
    "text":"Twitter", 
    "link":"www.Twiiter.com" 
    }, 
{ 
    "text":"Pinterest", 
    "link":"www.Pinterest.com" 
    }, 
    { 
    "text":"LinkedIn", 
    "link":"www.linkedin.com" 
    }] 

} 
} 
+0

你的回答是怎樣的?這將有助於說明爲什麼它不能正常工作:) – Alex

回答

0

需要聲明的類型的response

嘗試以下,

response => 

to 

(response : {prop: <string or what ever type>}) => 

這樣打字稿編譯器會知道什麼是你的反應對象的類型。

希望這有助於!

0

你的迴應可能看起來像json,但實際上是一個字符串。

檢查與

console.log(typeof response); 

類型嘗試也..

response.json() 

JSON.parse(response); 

您可能需要添加服務器響應的JSON響應頭。

+0

typeof響應是Object。 –

0

如上所述,您的響應是一個對象(在對象內),這就是爲什麼您需要使用console.log(response["prop"]);來訪問數據,因爲這是我們訪問嵌套對象的方式。

不知道你想要什麼,從你的回答中提取,如果你只是想在陣列,這樣做:

服務:

getData(url="this.Title"): Promise<{}> { 
    return this.http.get(url) 
     .toPromise() 
     .then(response => response.json().footerLinks['social']) 
     .catch(this.handleError); 
} 

如果你想保留對象social,其中包含該陣列僅將['social']從上面的代碼中排除。但我假設你只想要數組,因爲對象social實際上不包含除數組之外的其他任何內容。

組件:

links: any[] = []; 

this.httpService.getData("http://127.0.0.1:8887/footer.json") 
    .then(response => { 
    this.links = response; 
    }); 
} 

並可以迭代數組:我使用了safe navigation operator

<div *ngFor="let link of links"> 
    {{link?.text}} {{link?.link}} 
</div> 

通告,以防止應用投擲誤差在空值的情況下。