我需要在某个网址上预加载数据,所以 我解析了:
import {Injectable} from '@angular/core';
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router';
import {Observable} from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProfileResolver implements Resolve<any> {
constructor(
private _http: Http
) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any>|any {
return this._http.get('/session').map(data => {
console.log(data);
return data;
});
}
}
和组件:
import {Component} from '@angular/core';
import {RouterModule, ActivatedRoute} from '@angular/router';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Component({
selector: '[profile]',
host: {
class: 'profile-page app'
},
template: require('./profile.html')
})
export class Profile {
constructor(
private route:ActivatedRoute
) {
this.route.data.subscribe(data => {
console.log(data);
});
}
profile;
}
路线配置:
{
path: 'profile',
loadChildren: () => System.import('../profile/profile.module'),
resolve: {
profile: ProfileResolver
},
},
解析器中的 Console.log
显示收到的数据,但在组件中它是空的对象,有什么不对?当我在rc4中使用此代码时,一切都很好。
此外,如果我将return _http.get(...)
更改为简单值,例如return "123";
,则此代码将起作用。提前谢谢。
答案 0 :(得分:0)
获取数据可以(而且应该)通过
完成this.profile = this.route.snapshot.data['profile'];
可在此处找到完整和完整的说明: http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html