我是角色新手,我想在组件加载之前填充一些数据,所以我选择使用提供者工厂
COMPONENT
import { Component, AfterViewInit, APP_INITIALIZER } from '@angular/core';
import { SaModelService, initConfiguration } from './sa-model.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
{
provide: SaModelService,
useFactory: () => (data: SaModelService) => {
return data.load();
}
}
]
})
export class AppComponent implements AfterViewInit {
constructor(private data: SaModelService) {
}
ngAfterViewInit() {
alert(this.data)
}
}
服务
import { Injectable } from '@angular/core';
@Injectable()
export class SaModelService {
constructor() { }
load() {
return {
name: 'foo',
age: 10,
contact: '720 890 1430'
};
}
}
export function initConfiguration(configService: SaModelService): Function {
return () => configService.load();
}
现在当我运行这段代码时,我没有获得从函数返回的值对象,而是获得了函数,就像这样
如何获取值而不是函数
答案 0 :(得分:0)
不要真的知道你想在这里实现什么。如果目标是确保在角度加载之前加载初始数据,那么这就是你的工作方式:
在提供者中,请改用:
{
provide: APP_INITIALIZER, // imported from @angular/core
useFactory: requestInitialAppData, // Your function where you do stuff before angular loads
deps: [SaModelService] // Your service that will be injected to the function
multi: true
},
然后添加一个处理初始逻辑的函数。
requestInitialAppData(SaModelService) {
// Do your stuff here, and as I said, im not really sure what you ar trying to achieve here but this will give you a chance to populate data in services before angular loads.
}
以下是一份有用的指南:Angular 4 Tutorial - Run Code During App Initialization