将初始化数据传递给Angular 2

时间:2017-02-21 22:53:18

标签: angular

有没有人知道我可以将初始化数据传递到使用Angular CLI构建的Angular 2应用程序的方法?我需要从预先认证的.NET后端传递我目前拥有的访问令牌,以便我可以调用API。

我尝试通过本地web api端点执行此操作,但由于Observable是异步的,因此模块会尝试在应用程序中使用之前使用该值。

我已经尝试过@Ben Nadel Here的OnRun建议。我的http调用结果仍然在加载应用程序后发生,导致我的访问令牌在首次加载时为空。

下面提到的@Bilyachat之类的东西会很棒!在哪里我可以简单地做以下事情:

<app-root [apiKey]="1234567890xxxxx"></app-root>

任何帮助都会很棒......谢谢。

4 个答案:

答案 0 :(得分:3)

如果使用{},则返回config.load();

需要显式return
  useFactory: (config: AppConfig) => () => {
    return config.load();
  },

Plunker example

答案 1 :(得分:0)

如果您在MVC页面上有角度应用程序,那么我会看到两个选项

<强>第一 在角度根组件属性中(在第一个建议中我告诉你使用输入参数,但问题是根组件是&#34;超出角度&#34;并且它将无法读取参数唯一的方法是读取属性手动)

import {Component, NgModule, Input, ElementRef} from '@angular/core'
export class App {
   myConfig: any;
  constructor(element: ElementRef) {
    this.myConfig = element.nativeElement.getAttribute('data-config'); 
  }

}

然后当你打印时,你可以这样做

<app-root data-config="valueGoeshere"></app-root>

更新了plnkr

<强>第二

在mvc页面上打印

var yourAppMvcConfig= {
    configValue: 'DO_PRINT_HERE'
};

添加到src / typings.d.ts(如果缺少添加它)

declare var yourAppMvcConfig: {
    configValue: string;
}

在Angular中使用

yourAppMvcConfig.configValue

答案 2 :(得分:0)

“模块尝试在应用程序中使用之前使用该值” - 我认为这是您的问题。

相反延迟页面的加载,直到使用您的令牌的调用返回为止,为什么不编写在令牌返回之前不进行任何调用的代码?

ngOnInit() {
    this.tokenService.getToken().subscribe((token) => {
        console.log('now I have a token, and am ready to make my calls', token);

        this.secureService.getSecureDataUsingToken(token).subscribe((result) => {
            console.log('here is the result of the authenticated call', result);
        }
    });
}

答案 3 :(得分:0)

这是我找到的解决方案。您的index.html文件正好在angular开始加载脚本文件的位置。您可以添加以下行:

<script type="text/javascript">localStorage.setItem("title", "<?php echo $title; ?>")</script>

这会将数据放在客户端上的localstorage中,您可以在应用程序中检索。我正在使用php尝试在opencart商店中初始化一些内容。这是传递数据的好方法。如果你传入JSON,你需要在传入之前使用json.stringfy。当你从应用程序中检索它时,你需要做json.parse