将返回的 Observables 转换为角度的自定义类数组

大家好,我将通过显示代码使我的问题变得非常简单

  1. 我正在使用 Json 占位符站点作为假休息 Api

  2. 我有一个用户类对象

  3. 我想将返回的 Observable 转换为自定义类对象数组。

 import { Injectable } from '@angular/core';

    import { HttpClient } from '@angular/common/http';

    import { Observable } from 'rxjs';

    import { Users } from './users.model';

    

        @Injectable({

          providedIn: 'root'

        })

        export class UsersService {

        

          private url = "https://jsonplaceholder.typicode.com";

        

          constructor(private http:HttpClient) {

            console.log(this.getUsers());

           }

        

        

          getUsers():Observable<Users[]>{

            return this.http.get<Users[]>(`${this.url}/posts`);

        }

        

        }

以上是我的服务


    export class Users {

        email:          string;

        id:             number;

        name:           string;

        phone:          string;

        username:       string;

        

    }

以上是我的课程,我没有包含所有属性


在我的打字稿文件中,我有类似的代码。


constructor(private _usersService:UsersService) {

    

  }


  ngOnInit(): void {

   

    this._usersService.getUsers().subscribe(data=>this.users=data);


    console.log(this.users);

  }

现在我想要的是


如何在我的自定义类对象中转换返回的 observable?

我没有所有字段,那么如何仅映射我想要的那些字段?

希望我的问题很清楚..!!


HUH函数
浏览 118回答 1
1回答

慕少森

所以这个答案利用了从 rxjs 导入的 map() 。在订阅之前,我们将通过管道将 map() 函数传递到 observable 流中,然后将该数组中的每个元素 map() 到适合我们用户界面的新对象中然后我们订阅,我们得到的数据将是一个适合我们用户界面的数组ngOnInit(): void {&nbsp; &nbsp;&nbsp; &nbsp; this._usersService.getUsers()&nbsp; &nbsp; .pipe(map(data => {&nbsp; &nbsp; &nbsp; return data.map(item => {&nbsp; &nbsp; &nbsp; &nbsp; const user: User = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: item.name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email: item.email,&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return user&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }))&nbsp; &nbsp; .subscribe(data=>this.users=data);&nbsp; &nbsp; console.log(this.users);&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript