如何使用訂閱來映射對象 (How to map object using subscribe in angular)


問題描述

如何使用訂閱來映射對象 (How to map object using subscribe in angular)

我正在嘗試將值分配給我的組件中的類型。當我執行 console.log 時,我的訂閱正在恢復它

this.srvice.getTasks(this.request).subscribe(heroes => console.log(heroes));



{
    "List": [
        {
            "id": 17,
            "pro": 1,
            "name": "Ram",
            "UserId": 2,
            "duedate": "2018‑01‑01T00:00:00",
            "status": 1,
            "active": false
        },
        {
            "id": 3,
            "pro": 1,
            "name": "My Name",
            "UserId": 1,
            "duedate": "2018‑01‑01T00:00:00",
            "status": 2,
            "active": false
        },
    ]
}

但是當我執行任務時,它不起作用.. 我認為它需要提供直接列表,但我的對象包含在“列表”。我怎樣才能提取這個?我是角度新手

這就是我分配值的方式

組件類:

model: dtoModel = {
          List : []
       };

 this.taskService.getTasks(this.request).subscribe(heroes => this.model = heroes);

模型

export interface dto {
    id: number;
    pro: number;
    name: string;
    UserId: number;
    duedate: string;
    status: number;
    active: boolean;
  }

export interface dtoModel {
    List: dto[];
}

服務中

getTasks (requestSearch: TaskRequest): Observable<dto[]> {
        return this.http.post<dto[]>(this.Url, requestSearch,  httpOptions);
}

參考解法

方法 1:

You can just use

this.taskService.getTasks(this.request).subscribe(heroes => this.model = heroes.List);

and that will select the List array.

And the model will become

model: dto[] = [];

方法 2:

Can you please do your thing like this way.

 this.srvice.getTasks(this.request)
 .map(data =>{
   //do your logic and convert the data accordingly.
   // then result will be sent to subscribe block
  })
 .subscribe(result =>{
 });

方法 3:

You can also use map operator in rxjs for this if you need to reuse this getTasks method.

map :Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.

// In your service method
getTasks() {
  return this.http.get(<url>)
    .pipe(map(tasksObj=> {

       return tasksObj.List;
    }));
}

If you are using angular 5 use below

getTasks() {
  return this.http.get(<url>)
    .pipe(map(tasksObj=> {

       return tasksObj.List;
    }));
}

Checkout this Stackblitz example. Learn more about map operator here.

方法 4:

You should create 2 interfaces like below:

export interface dtoModel = {
   List : ListItem[]
};

export interface ListItem {
    id: number;
    pro: number;
    name: string;
    UserId: number;
    duedate: string;
    status: number;
    active: boolean;
}

Then you can set up types for you request this way:

getTasks (requestSearch: TaskRequest): Observable<dtoModel> {
    return this.http.post<dtoModel>(this.Url, requestSearch,  httpOptions);
}

If all you request returns json with List field I sugest you to use generic type:

 export interface dtoModel<T> = {
       List : <T>[]
 };

 export interface ListItem {
        ....
 }

And request will look like this:

getTasks (requestSearch: TaskRequest): Observable<dtoModel<ListItem>> {
        return this.http.post<dtoModel<ListItem>>(this.Url, requestSearch,  httpOptions);
}

(by SweetieDzhavat UshevAnkur ShahSenalDmitriy Kavraiskyi)

參考文件

  1. How to map object using subscribe in angular (CC BY‑SA 2.5/3.0/4.0)

#angular7 #subscribe #Angular #angular2-services






相關問題

更改角度 7 中打印值的顏色 (Change the colour of printed value in angular 7)

在Angular7中更改路線的頁面重新加載問題 (Page reload issue on changing the route in Angular7)

如何使用訂閱來映射對象 (How to map object using subscribe in angular)

Angular 文件夾結構 (Angular Folder Structure)

在兄弟組件之間傳遞數據 (Passing Data between sibling components)

如何在 *ngFor 中循環選擇標籤並獲取所選值 (how to loop throught select tags inside *ngFor and get the selected value)

如何測試角度事件監聽器? (How to test angular event listeners?)

Angular 7/8 響應開發服務器上的健康檢查 (Angular 7/8 respond to health-checks on the dev server)

NgRx Store:如何在兩個功能模塊之間共享數據 (NgRx Store : How to share the data between two feature modules)

根據角度表單構建器/組中其他字段的值運行並設置一個字段的驗證錯誤 (Run and set the validation errors on one field based on the value of other field in angular form builder/group)

如何更改 Angular Material 中的標籤標籤? (How to change tab label in Angular Material?)

429 Too Many Requests - Angular 7 - 多個文件上傳 (429 Too Many Requests - Angular 7 - on multiple file upload)







留言討論