我有这个服务从django rest api获取对象列表。
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import {environment} from '../../../environments/environment';
import {Delegation} from "../delegations/delegation";
@Injectable()
export class DelegationsService {
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
getDelegations(userid: number) {
return this.http.get(environment.apiUrl + '/api/v1/delegations/' + userid )
.map(res => <Delegation[]>res.json());
}
}
../delegations/delegation.ts
的内容是:
export class Delegation {
id: number;
delegator: number;
delegatee: number;
}
委托人和委托人的号码是“用户”的数据库ID。我需要显示通过另一个REST API网址提供的实际用户名和登录ID。我以为我可以将../delegations/delegation.ts
修改为:
export class Delegation {
id: number;
delegator: number;
delegator_login: string;
delegator_name: string;
delegatee: number;
delegatee_login: string;
delegatee_name: string;
}
然后我会迭代我从this.http.get(environment.apiUrl + '/api/v1/delegations/' + userid )
调用获得的元素并请求用户信息,但我不知道如何对结果集进行迭代。
更新:
目前我可以将委托者数据转储到我的delegation.component.html模板和网页显示:
2 | 97597 | 5197
4 | 97597 | 9757
我想要展示的是:
2 | Sam Smith (ssmith) | Lisa Butts (lbutts)
4 | Sam Smith (ssmith) | Bill Fatlips (bfatlips)
我的delegations.component.html
非常简单:
<ul class="delegations">
<li *ngFor="let delegation of delegations" [class.selected]="delegation === selectedDelegation" (click)="onSelect(delegation)">
<span class="badge">{{delegation.id}}</span> | {{delegation.delegator}} | {{delegation.delegatee}}
</li>
</ul>
它几乎就是他们在Heroes Angular tut中所拥有的:https://angular.io/tutorial/
答案 0 :(得分:0)
尝试这样做:
getDelegations(userid: number) {
return this.http.get(environment.apiUrl + '/api/v1/delegations/' + userid )
.map(res => {
const theList = <any[]>res.json();
theList.forEach(item => {
this.http.get(environment.apiUrl + '/api/v1/delegaor/' + item.delegator)
.map(res2 => {
const delegator = res2.json();
item.delegator_login = delegator.login;
item.delegator_name = delegator.name;
});
this.http.get(environment.apiUrl + '/api/v1/delegatee/' + item.delegatee)
.map(res3 => {
const delegatee = res3.json();
item.delegatee_login = delegatee.login;
item.delegatee_name = delegatee.name;
})
})
return theList;
} )
.subscribe(finalList => {
// this finalList is your delation list with names and logins and ids
});
}
我有点担心在发出内部api调用之前会返回finalList,但我认为订阅会在返回之前等待所有内容完成。当然,这个解决方案是假设您将字符串添加到委托类中。