我正在检索用户信息以显示配置文件页面,并且我使用路由解析来执行此操作,但解决方法由于某种原因将用户置于数组中。如何使解析返回单个对象?
声明并提供所有服务,模块,结果和组件
型号:
JsonConvert.SerializeObject(configItem)
服务方式:
/**
* Builds a user from the provided parameters
* @param {string} id of the user
* @param {string} username of the user
* @param {string} password of the user
* @param {string} apiKey of the user
* @param {string[]} roles of the user to give certain rights
*/
export class User {
id: string;
username: string;
password: string;
apiKey: string;
roles: string[];
constructor(id: string, username: string, password: string, apiKey: string, roles: string[]) {
this.id = id;
this.username = username;
this.password = password;
this.apiKey = apiKey;
this.roles = roles;
}
}
解决课程:
findByApiKey(): Observable<User> {
const headers = new Headers();
headers.append('Accept', 'application/smartask.usersv2+json');
headers.append('api-key', this.authenticationService.getApikey());
const options = new RequestOptions({
headers: headers
});
const url = `${this.url}?apikey=${this.authenticationService.getApikey()}`;
return this.http.get(url, options)
.map((response: Response) => {
return (<any>response.json()).map(user => {
return new User(
user.id,
user.username,
user.password,
user.apiKey,
user.roles
);
});
}, {headers: headers});
}
组件:
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve} from '@angular/router';
import {User} from '../models/user.model';
import {UserService} from '../providers/user.service';
@Injectable()
export class UserResolve implements Resolve<User> {
constructor(private userService: UserService) {
}
resolve(route: ActivatedRouteSnapshot) {
return this.userService.findByApiKey();
}
}
答案 0 :(得分:1)
根据评论,问题是API返回包含用户对象的数组。如果您无法更改,可以将map
更改为:
return this.http.get(url, options)
.map(response => response.json()) // this is no longer necessary in latest angular
.map(user => user && user[0])
.map(userData => userData && new User(
userData.id,
userData.username,
userData.password,
userData.apiKey,
userData.roles
), {headers: headers});