有没有一种方法可以在将Angular 4服务的数据注入组件之前对其进行解析? [英] Is there a way to resolve data for an Angular 4 service before it's injected into a component?
问题描述
我是Angular 2/4的新手,所以请原谅我的无知.我有一个要注入到各种组件中的服务,但是该服务使用的元数据需要首先从服务器中检索.我想知道是否有一种方法可以确保在将服务注入组件之前就已经解析了该服务的数据.
I'm new to Angular 2/4, so please forgive my ignorance. I have a service that I want to inject into various components, but this service uses meta data that needs to be retrieved from the server first. I'd like to know if there's a way to ensure the data for the service is resolved before the service gets injected into the components.
我读了一些有关路由警卫的信息,听起来与我想要的类似,但是我认为这不适用于我的问题,因为服务本身没有路由.
I read a little about route guards which sounds similar to what I'm looking for, but I don't think that applies to my problem since the service itself doesn't have a route.
推荐答案
在激活路线和组件之前,Angular 2/4中的解析用于获取数据.
UserResolve服务从服务器获取数据.
UserResolve service gets data from the server.
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot} from '@angular/router';
import { UserService } from '../services/user.service';
@Injectable()
export class UserResolve implements Resolve<any> {
constructor(private service: UserService) {}
resolve(route: ActivatedRouteSnapshot) {
return this.service.getUser().then(user => user);
}
}
注意:在模块中导入"UserResolve",并在提供程序中使用它(如下所示).
Note: Import the "UserResolve" in your module and use it in providers (shown below).
.......
import { UserService } from '../services/user.service';
import { UserResolve } from './user.resolve';
@NgModule({
imports: [ ... ],
declarations: [HomeComponent, AboutComponent, AboutUserComponent],
providers: [UserService, UserResolve]
})
export class UserModule { }
在路由器模块中使用它在组件加载之前调用服务(解析数据).
Use it in router module to call service (resolves data) before the component loads.
const aboutRoutes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{
path: '',
component: AboutComponent,
resolve: {
user: UserResolve
}
},
{
path: 'user',
component: AboutUserComponent
}
]
}
]
谢谢...
这篇关于有没有一种方法可以在将Angular 4服务的数据注入组件之前对其进行解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!