简体   繁体   English

将返回的 Observables 转换为 angular 中的自定义 class 数组

[英]convert returned Observables to custom class array in angular

Hello folks I will keep my question very simpler by showing code大家好,我将通过显示代码使我的问题变得非常简单

  1. I am using Json placeholder site for the fake rest Api我正在为假 rest Api 使用 Json 占位符站点
  2. I have a user class Object我有一个用户 class Object
  3. I want to convert returned Observable to the custom class object array.我想将返回的 Observable 转换为自定义 class object 数组。
    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`);
        }
        
        }

The above is my service以上是我的服务

    export class Users {
        email:          string;
        id:             number;
        name:           string;
        phone:          string;
        username:       string;
        
    }

above is my class I haven't included all properties以上是我的 class 我没有包括所有属性

In my typescript file I have code like.在我的 typescript 文件中,我有类似的代码。

constructor(private _usersService:UsersService) {
    
  }

  ngOnInit(): void {
   
    this._usersService.getUsers().subscribe(data=>this.users=data);

    console.log(this.users);
  }

Now the things I want is现在我想要的是

  1. how to convert returned observable in my custom class object?如何在我的自定义 class object 中转换返回的 observable?
  2. I don't have all the fields so how is it possible to map only those fields which I want?我没有所有字段,那么 map 怎么可能只有我想要的那些字段?

Hope my question is clear..!!希望我的问题很清楚..!!

so this answer takes advantage of map() which is imported from rxjs.所以这个答案利用了从 rxjs 导入的 map()。

before subscribing we are going to pipe a map() function into the observable stream and then map() each element from that array into a new object that fits our User interface before subscribing we are going to pipe a map() function into the observable stream and then map() each element from that array into a new object that fits our User interface

then we subscribe and the data we get then will be an array that fits our User interface然后我们订阅,我们得到的数据将是一个适合我们用户界面的数组

 ngOnInit(): void { this._usersService.getUsers().pipe(map(data => { return data.map(item => { const user: User = { name: item.name, email: item.email, } return user }) })).subscribe(data=>this.users=data); console.log(this.users); }

You can do like below, in the User class have a constructor and return User while mapping您可以像下面这样,在User class 有一个构造函数并在映射时返回User

import { Component, VERSION, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

export class User {
    email: string;
    id: number;
    name: string;
    phone: string;
    username: string;

    constructor( user: User ) {
      Object.assign( this, user );
    }
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent implements OnInit  {
  name = 'Angular ' + VERSION.major;

  constructor(private http: HttpClient){}

  ngOnInit() {
    this.http.get<User[]>("https://jsonplaceholder.typicode.com/users")
    .pipe(
      map( data => {
        return data.map( ( user ) => {
          return new User( {
            email: user['email'],
            id: user['id'],
            name: user['name'],
            phone: user['phone'],
            username: user['username'],
          } );
        } );
      } ),
    )
    .subscribe( (users : User[]) => console.log(users) );
  }
}

Working stackblitz工作堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM