Get array from response instead of Object

十年热恋 提交于 2020-01-25 07:28:07

问题


I am trying to get only specific items from my database then display it in table.

This is how my sql query looks like

public async aliasesListByDomain(req: Request, res: Response): Promise<void> {
    const { domain } = req.params;
    const aliases = await pool.query('SELECT * FROM virtual_aliases INNER JOIN virtual_domains ON virtual_aliases.domain_id = virtual_domains.id WHERE virtual_aliases.domain_id = ?', [domain]);
    if (aliases.length > 0) {
        res.json(aliases);
    } else {
        res.status(404).json({ message: "Alias doesn't exists" });
    }
}

There is my Aliases.service

 getAliasesByDomain(domain: string): Observable<Alias> {
    return this.http.get(`${this.API_URI}/aliases/aliaseslistbydomain/${domain}`);
  }

And there is my component

 getAliasesByDomain() {
    const token = this.getToken();
    let user;
    let domain;
    console.log(token);
    if(token){
      user = token.split('.')[1];
      user = window.atob(user);
      user = JSON.parse(user);
      domain = user.domain;

    }
    this.aliasesService.getAliasesByDomain(domain).subscribe(
      res => {
        this.alias = res;
      },
      err => console.error(err)
    );
  }

and component html

<tr *ngFor="let aliases of alias;">

My problem is that I got error:

AliasesListComponent.html:17 ERROR Error: Cannot find a differ supporting object 'to sa aliases: [object Object],[object Object]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

Because my response is Object object instead of array. How can I parse this?


回答1:


If your callback gives you an array you can just specify it inside the service like this

 getAliasesByDomain(domain: string): Observable<Alias[]> {
    return this.http.get<Alias[]>(`${this.API_URI}/aliases/aliaseslistbydomain/${domain}`);
  }



回答2:


If the server's response does not match the data model you are expecting, you can transform the response using rxjs.

import { map } from 'rxjs/operators';

getAliasesByDomain(domain: string): Observable<Alias[]> {
    return this.http.get(`${this.API_URI}/aliases/aliaseslistbydomain/${domain}`).pipe(
        map((response: any) => {
            return transform(response);
        })
    );
}

transform(response: any): Alias[] {
    // your translation logic here
}


来源:https://stackoverflow.com/questions/59159035/get-array-from-response-instead-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!