问题
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