1
私はプロファイルページを表示するためにユーザー情報を取得していますが、これを行うにはroute resolveを使用しますが、resolveメソッドはユーザーを何らかの理由で配列に置きます。解決方法を単一のオブジェクトに戻すにはどうすればよいですか?Angular2 route resolveは単一のオブジェクトの代わりに常に配列を返します
すべてのサービス、モジュール、解決し、コンポーネントが宣言され、提供され
モデル:
/**
* 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();
}
}
コンポーネント:
import {Component, OnInit} from '@angular/core';
import {User} from '../../models/user.model';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: User;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.user = this.route.snapshot.data['profile'];
console.log('user', this.user);
}
}
APIの生の応答を確認する必要があります。それはおそらく1つのユーザーオブジェクトを含む配列 – PierreDuc
@PierreDucこれは実際に問題です...ありがとう –