0

我是 Angular 新手,我想在加载组件之前填充一些数据,所以我选择使用提供程序工厂

零件

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();
}

现在当我运行这段代码时,我得到的不是从函数返回的值对象,而是函数,就像这样

在此处输入图像描述

我怎样才能得到值而不是函数

4

1 回答 1

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

于 2018-01-23T08:51:23.917 回答