問題描述
如何使用訂閱來映射對象 (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 Sweetie、Dzhavat Ushev、Ankur Shah、Senal、Dmitriy Kavraiskyi)