簡體   English   中英

Angular & RxJs: How to map json to Object Array

[英]Angular & RxJs : How to map json to Object Array

I try to map a Json http request answer to an object array (User) using RxJs:

我的 Json 數據如下所示:

{"@context":"\/cotabe\/api\/contexts\/User","@id":"\/cotabe\/api\/users","@type":"hydra:Collection","hydra:member":[{"@id":"\/cotabe\/api\/users\/1","@type":"User","id":1,"email":"a.a@gmail.com","firstname":"Aaa","lastname":"Ggg","phone":"0606060606","mobile":"0606060607","fullName":"Aaa Ggg","username":"a.a@gmail.com","roles":["ROLE_DEVROOT","ROLE_USER"],"password":"$argon2i","createdAt":"-0001-11-30T00:00:00+01:00","updatedAt":"-0001-11-30T00:00:00+01:00","deleted":false}],"hydra:totalItems":1}

我想從中提取一個用戶 [],用戶為 model:

export class User {
  constructor(
    public id: number,
    public email: string,
    public firstname: string,
    public lastname: string,
    public phone: string,
    public mobile: string,
    public roles: string[],
  ) {}
}

在我的用戶服務中,我有:

export class UserService {

  private users: User[] = [];
  userSubject = new Subject<User[]>();

  constructor(private apiService: ApiService) { }

  emitUsers() {
    this.userSubject.next(this.users.slice());
  }

  getUsersFromRest() {
    this.apiService.getEntriesFromRest('users').subscribe(
    (data: User[])=>{
      this.users = data['hydra:member'];
    });
    this.emitUsers();
  }
}

在 api 服務中

  public getEntriesFromRest (option: string): any {
    return this.httpClient.get<any[]>(this.baseEndpoint + option);
  }

我知道這是一個 rXjs 運算符的東西,但我沒有設法找到解決方案。 謝謝您的幫助,

export class UserService {
  userSubject = new Subject<User[]>();
  userSubject$ = this.userSubject.asObservable();
  constructor(private apiService: ApiService) {}

  getUsersFromRest() {
    this.apiService
      .getEntriesFromRest("users")
      .pipe(
        map(x => JSON.stringify(x)),
        map(x => JSON.parse(x)),
        pluck("hydra:member")
      )
      .subscribe((data: User[]) => {
        this.usersSubject.next(data);
      });
  }
}

可以試試上面的代碼嗎

export class UserService {

  private userSubject = new Subject<User[]>();
  userSubject$ = this.userSubject.asObservable(); // If you add a public observable of your subject, you can have other components subscribe to this, and not be able to alter the subject, but still get the data.

  constructor(private apiService: ApiService) { }

  getUsersFromRest() {
    this.apiService.getEntriesFromRest('users')
      .pipe(
        map((x: any) => JSON.parse(x)) // Convert your response from JSON to an Object
      .subscribe(
        (data: User[]) => {
          this.usersSubject.next(data.hydra.member);
        });
      }
  }

不需要單獨的發出用戶方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM