2017-09-13 72 views
0

當我調用本地服務器上的GET方法(http://localhost:51085/api/GetMethod)時,我的Web APPI正常工作,它將檢索正確的對象數組。Angular 4 + Web API無法使用GET方法檢索數據

但是,當我把它從Angular4應用程序,返回的可觀測顯示

[object Object] and an error for *ngFor (ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.).

export class AppComponent { 

    myDesiredDataFromServer$; 

    constructor(private service: ServiceHTTP) { 
     this.myDesiredDataFromServer = service.getData(); 
    } 
} 

任何幫助嗎?

+0

您可以爲Angular 4添加代碼嗎? –

+0

你還可以發佈你的API數據的樣本嗎? – rick

+0

如果你正在返回一個observable,在ngFor中使用異步管道來映射它 – JayDeeEss

回答

1

我覺得你的問題是你不等待服務器的響應..

如果你的.TS服務返回一個Observable<Array<any>>

這樣試試:

export class AppComponent { 

     myDesiredDataFromServer$; 



constructor(private service: ServiceHTTP) { 


     service.getData().subscribe((resp)=>{ 
      this.myDesiredDataFromServer = resp; 
     }); 
     } 
    } 

如果它正在退貨Promise<Array<any>>

export class AppComponent { 

     myDesiredDataFromServer$; 

     constructor(private service: ServiceHTTP) { 
      service.getData().then((resp)=>{ 
      this.myDesiredDataFromServer = resp; 
      }); 
     } 
    } 

if它返回一個async

export class AppComponent { 

     myDesiredDataFromServer$; 

     async constructor(private service: ServiceHTTP) { 
     this.myDesiredDataFromServer = await service.getData(); 
     } 
    } 
+0

謝謝Federico.I試試吧。 – GCoe

+0

讓我現在如果它的工作..如果你可以張貼您的服務代碼 –

+0

訂閱後,我可以看到返回的「_body」屬性正確返回的數據數組與service.getData()。subscribe((resp) => { this.myDesiredDataFromServer $ =((resp)['_ body']); console.log(「Ret - >」,this。myDesiredDataFromServer $); });但是不能用* ngFor - > ERROR顯示錯誤:InvalidPipeArgument:'[{「Date」:「2017-09-13T00:00:00」,... etc(顯示我的數據數組) – GCoe

0

嘗試

export class AppComponent { 
 

 
    public myDesiredDataFromServer$; 
 

 
    constructor(private service: ServiceHTTP) { 
 
     this.myDesiredDataFromServer$ = service.getData(); 
 
    } 
 
}

那麼,如果它的嘗試可觀察到下面的模板打印出完整的對象並不僅僅是[對象的對象]

{{ myDesiredDataFromServer$ | async | json }}

如果你的ServiceHTTP getData方法返回一個observable,那麼你應該至少能夠看到你所獲得的數據格式。如果您正在使用它,請確保其類型爲

例如,如果打印{someKey:[]},那麼你可以運行* ngFor = 「讓(myDesiredDataFromServer $ |異步)的項目?someKey」

+0

嗨,Daniel,我的數據在響應_body屬性中,但無法使用* ngFor - > ERROR錯誤:InvalidPipeArgument:'[{「Date」:「2017-09-13T00:00:00」,...等與我的陣列數據 – GCoe

+0

所以在你的模板{{myDesiredDataFromServer $ |異步| json}}顯示該對象?如果是這樣,請嘗試

Looped

+0

if'{{myDesiredDataFromServer $ |異步| json}}'displays {response_body: [{「Date」:「2017-09-13T00:00:00}]}然後嘗試'

Looped
' –

0

這工作:

service.getData().subscribe((resp)=>{ 
    this.myDesiredDataFromServer$ = JSON.parse((resp)['_body']); 

});

enter code here