代码之家  ›  专栏  ›  技术社区  ›  Fletch

在角度6中链接应用程序初始值设定项函数

  •  0
  • Fletch  · 技术社区  · 6 年前

    在使用Angular6和TypeScript时,我试图确保在应用程序启动之前加载两个配置项。我想从配置文件中检索一个API端点,然后使用该API端点来检索一些权限。然后,权限决定了屏幕上应该显示什么,所以我真的希望在应用程序之前加载它们。

    我读过几篇关于这个的文章,包括 APP_INITALIZER won't delay initialization , Runtime configuration Nested HTTP Requests . 然而,它们似乎都要求有一个config.service.ts来处理所需的所有配置加载。让一个服务加载API端点(和其他配置片段)和另一个服务访问API不是更好的做法吗?

    我把一个 Plunker 它演示了两个独立的服务来检索信息。控制台正在记录各个步骤。电流输出为:

    going to load app settings
    getting permissions
    undefined (This is the api endpoint retrieved from the config file)
    Angular is running in the development mode. Call enableProdMode() to enable the production mode. 
    got appsettings
    

    我希望您能看到代码正在尝试加载端点,并尝试使用它同时检索权限。该端点实际上是在加载应用程序后检索的。我希望先检索API端点,然后加载权限,然后加载应用程序。因此,所需的输出是:

    going to load app settings
    got appsettings
    getting permissions
    https://webapi.endpoint/
    Angular is running in the development mode. Call enableProdMode() to enable the production mode.
    

    我对棱角很陌生,所以任何帮助或指点都会受到感激。

    编辑: 我找到了这个 post 但我不明白解决办法。如果有人能帮我拔掉它,这似乎很有关系?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Fletch    6 年前

    最后我从 hackernoon 重新安排了我的承诺。我保留了单独的服务,但从AppSettings服务调用了权限服务。

    应用程序设置.service.ts:

    loadAppSettings() {
    
    return (): Promise<any> => {
      return new Promise((resolve, reject) => {
        console.log('loadAppSettings:: inside promise');
    
        setTimeout(() => {
          console.log('loadAppSettings:: inside setTimeout');
          this.permissionService.loadPermissions().then(x=> resolve());
        }, 5000);
    
      })
    }
    

    权限.service.ts:

    loadPermissions() {
      return new Promise((resolve, reject) => {
        console.log(`PermissionsService:: inside promise`);
    
        setTimeout(() => {
          console.log(`PermissionsService:: inside setTimeout`);
          resolve();
        }, 3000);
      });
    }