[英]convert returned Observables to custom class array in angular
大家好,我将通过显示代码使我的问题变得非常简单
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;
}
以上是我的 class 我没有包括所有属性
在我的 typescript 文件中,我有类似的代码。
constructor(private _usersService:UsersService) {
}
ngOnInit(): void {
this._usersService.getUsers().subscribe(data=>this.users=data);
console.log(this.users);
}
现在我想要的是
希望我的问题很清楚..!!
所以这个答案利用了从 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
然后我们订阅,我们得到的数据将是一个适合我们用户界面的数组
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); }
您可以像下面这样,在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) );
}
}
工作堆栈闪电战
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.