我该如何解析,以便使用Angular解析返回对象本身而不是Observable <object>?

时间:2018-11-11 21:03:51

标签: angular

我有一个看起来像这样的解析器:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';

import { User } from './user';

@Injectable()
export class UserResolver implements Resolve<User> {

    constructor(private httpClient: HttpClient) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User> {
        const userId = +route.params['userId'];
        return this.httpClient.get<User>('/api/user/single/userId/' + userId);
    }
}

我在RouterModule中像这样使用它:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { SmsComponent } from './sms.component';
import { SmsSentComponent } from './sms-sent/sms-sent.component';
import { SmsNewComponent } from './sms-new/sms-new.component';
import { SmsPlannedComponent } from './sms-planned/sms-planned.component';

import { UserResolver } from '../users/user.resolver';

const routes: Routes = [
    {
        path: '',
        component: SmsComponent,
        children: [
            { path: 'sent', component: SmsSentComponent },
            // https://stackoverflow.com/questions/34208745/angular-2-optional-route-parameter
            { path: 'new/:userId', component: SmsNewComponent, resolve: { user: UserResolver } },
            { path: 'new', component: SmsNewComponent },
            { path: '', component: SmsPlannedComponent }
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule],
    providers: [
        UserResolver
    ]
})
export class SmsRoutingModule { }

然后我在这样的组件内的ngOnInit()内部获取用户:

this.activatedRoute.data
    .subscribe((user: User) => {
        console.log(user);
    });

当我用console.log用户登录时,它似乎可以工作,但是如果我用console.log登录,则:

this.activatedRoute.data
    .subscribe((user: User) => {
        console.log(user.cellphone);
    });

然后我变得不确定。当我运行console.log时,用户似乎还没有准备好,难道不是解决组件加载时准备就绪的全部问题吗?如何按预期在ngOnInit()中准备好用户对象?

这是User类:

export class User {
    constructor(
        public id: number = 0,
        public email: string = '',
        public firstname: string = '',
        public lastName: string = '',
        public cellphone: string = '',
        public companyName: string = '',
        public address: string = '',
        public hasHeating: boolean = false,
        public heatingLastService: string = '',
        public createdTime: number = 0,
        public isCreatedByAdmin: boolean = false,
        public isDeleted: boolean = false
    ) { }
}

0 个答案:

没有答案