javascript - 无法使用 Angular 2.0.0 解析来自 http.get() 的数据

标签 javascript angular angular2-routing

我需要在某些网址上预加载数据,所以 我有解析器:

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"; ,此代码将起作用。提前致谢。

最佳答案

获取您的数据可以(并且应该)通过

this.profile = this.route.snapshot.data['profile'];

完整的解释可以在这里找到: http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

关于javascript - 无法使用 Angular 2.0.0 解析来自 http.get() 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975276/

相关文章:

javascript - console.log 打印数据两次 [reactjs]

javascript - 有没有办法将 jquery 函数包装到对象中?

testing - 在生产模式下隐藏 angular2 组件的最佳解决方案?

Angular2 保留/添加尾部斜线

javascript - react.js 替换 img src onerror

javascript - header无法使用跨域传入ajax

javascript - 为什么不在 app.component 中工作,而是在 auth.guard 中工作?

json - Angular 2 导入 Http 失败

html - 具有 DOM 元素 ID 的 href 不适用于 Angular

javascript - 更新到 angular2 beta.1 后,路由器不再工作。它在 beta.0 中做到了