将初始化数据传递给 Angular 2 [英] Passing Initialization Data to Angular 2

查看:21
本文介绍了将初始化数据传递给 Angular 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know a way that I can pass initialization data into an Angular 2 application built with Angular CLI? I need to pass Access Token that I currently have from a pre-authenticated .NET backend so that I can call an API.

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

I've tried to do this via a local web api endpoint, but since Observables are async, the module tries to use the value before it's available in the app.

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

I've already tried the OnRun suggestion by @Ben Nadel Here. The result of my http call still happens AFTER the app is loaded causing my access token to be null when it first is loaded.

下面建议的@Bilyachat 之类的东西会很好用!我可以简单地执行以下操作:

Something like @Bilyachat suggested below would work great! Where I could simply do something like the following:

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

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

Any help would be awesome... Thanks.

推荐答案

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

If you have angular app on MVC page then i see two options

第一在角度根组件属性中(在第一个建议中,我告诉您使用输入参数,但问题是根组件超出角度"并且无法读取参数,唯一的方法是手动读取属性)

First In angular root component attribute (In first suggestion i told you to use input parameters, but problem is that root component is "Out of angular" and it will not be able to read parameters the only way is to read attributes manually)

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

}

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

Then when you print you can do like this

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

更新了plnkr

第二

在 mvc 页面上打印

Print on mvc page

var yourAppMvcConfig= {
    configValue: 'DO_PRINT_HERE'
};

添加到src/typings.d.ts(如果没有添加)

add into src/typings.d.ts (If its missing add it)

declare var yourAppMvcConfig: {
    configValue: string;
}

在 Angular 中使用

Use in Angular

yourAppMvcConfig.configValue

这篇关于将初始化数据传递给 Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆