iT邦幫忙

0

angular http get 資料 給 typescript

Zaku 2018-08-27 11:18:294216 瀏覽

假定我有個結構長這樣:

export class a {
  public id: any;
  public time: string;
  public full: Date;
  constructor(id:any, name:string, time:string){
    this.time = time;
    this.name = name;
    this.id = id; 
    this.full = new Date(time);
  }
}

這邊去伺服器撈資料

saveData:a[] =[];

this.http.get<any>("http://localhost/api/data/get").pipe(map(data => {
    return {
        d:{
            id: data._id,
            name: data.name,
            time: data.time
        }
    }
})).subscribe(transforme=> {
    this.saveData = transforme.d;
});

錯誤會寫是

[ts]
類型 '{ id: any; name: any; time: any;}' 不可指派給類型 'a[]'。
  類型 '{ id: any; name: any; time: any;}' 遺漏屬性 'length'。
this: this

好饒舌...,不知道是遺漏了什麼,不能直接這樣餵?遺漏屬性 'length'這是??

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Homura
iT邦高手 1 級 ‧ 2018-08-27 14:21:08
最佳解答

改這樣試試

saveData:Array<a> = new Array();

this.http.get<any>("http://localhost/api/data/get").pipe(map(data => {
    return {
        d:{
            id: data._id,
            name: data.name,
            time: data.time
        }
    }
})).subscribe(transforme=> {
    this.saveData.push(transforme.d);
});
看更多先前的回應...收起先前的回應...
froce iT邦大師 1 級 ‧ 2018-08-27 16:10:57 檢舉

看了一下程式碼,感覺跟RxJS好像。

Homura iT邦高手 1 級 ‧ 2018-08-27 16:21:14 檢舉

froce
查了一下就是RxJS喔
這篇有提
https://ithelp.ithome.com.tw/articles/10186103

Zaku iT邦新手 3 級 ‧ 2018-08-29 13:57:14 檢舉

感謝大大,我應該是要先new a 出來存資料後,再this.saveData.push進去,差不多意思

Homura iT邦高手 1 級 ‧ 2018-08-30 09:06:35 檢舉

有解決就好

我要發表回答

立即登入回答