GVKun编程网logo

angular2-routing – 如何在bootstrap动态提供路由?(angular动态路由配置)

18

对于angular2-routing–如何在bootstrap动态提供路由?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angular动态路由配置,并且为您提供关于Angular2–ng

对于angular2-routing – 如何在bootstrap动态提供路由?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angular动态路由配置,并且为您提供关于Angular 2 – ng-bootstrap如何为其NgbRadio指令提供NgbRadioGroup和NgbButtonLabel?、Angular 2在Bootstrap之前解析服务、Angular 学习系列 - - angular.bind、angular.bootstrap、angular.copy、angular-cli创建angular2项目并添加ng2-bootstrap的宝贵知识。

本文目录一览:

angular2-routing – 如何在bootstrap动态提供路由?(angular动态路由配置)

angular2-routing – 如何在bootstrap动态提供路由?(angular动态路由配置)

如何为RouterModule提供服务,以便根据某些参数动态注入路由?

请注意,此参数也是动态的(它来自bootstrapping之前的api调用).

我确实意识到通过使用RouterModule.forRoot(这是一个静态函数),我对注入服务非常有限.

解决方法

您需要为ROUTES标记提供一个生成路由配置并获取该参数的函数.此外,您需要提供该参数.

import {ROUTES} from '@angular/router/src/router_config_loader';
[...]
imports: [RouterModule.forRoot([])] // Empty on purpose
providers: [
  SomeParamForTheFunction,{provide: ROUTES,multi: true,useFactory: routesFunction,deps: [SomeParamForTheFunction]},]

你如何提供这个参数取决于你.你可以使用另一家工厂.

更新:由于路由配置现在是动态的,因此您还必须提供entryComponents属性以及初始页面加载所需的所有组件.

Angular 2 – ng-bootstrap如何为其NgbRadio指令提供NgbRadioGroup和NgbButtonLabel?

Angular 2 – ng-bootstrap如何为其NgbRadio指令提供NgbRadioGroup和NgbButtonLabel?

这是标签代码:
import {Directive} from '@angular/core';

@Directive({
  selector: '[ngbButtonLabel]',host:
      {'[class.btn]': 'true','[class.active]': 'active','[class.disabled]': 'disabled','[class.focus]': 'focused'}
})
export class NgbButtonLabel {
  active: boolean;
  disabled: boolean;
  focused: boolean;
}

这是单选按钮代码:

import {Directive,forwardRef,Input,Renderer2,ElementRef,OnDestroy} from '@angular/core';
import {ControlValueAccessor,NG_VALUE_ACCESSOR} from '@angular/forms';

import {NgbButtonLabel} from './label';

const NGB_RAdio_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => NgbRadioGroup),multi: true
};

let nextId = 0;

/**
 * Easily create Bootstrap-style radio buttons. A value of a selected button is bound to a variable
 * specified via ngModel.
 */
@Directive({
  selector: '[ngbRadioGroup]',host: {'data-toggle': 'buttons','role': 'group'},providers: [NGB_RAdio_VALUE_ACCESSOR]
})
export class NgbRadioGroup implements ControlValueAccessor {
  private _radios: Set<NgbRadio> = new Set<NgbRadio>();
  private _value = null;
  private _disabled: boolean;

  get disabled() { return this._disabled; }
  set disabled(isdisabled: boolean) { this.setdisabledState(isdisabled); }

  /**
   * The name of the group. Unless enclosed inputs specify a name,this name is used as the name of the
   * enclosed inputs. If not specified,a name is generated automatically.
   */
  @input() name = `ngb-radio-${nextId++}`;

  onChange = (_: any) => {};
  onTouched = () => {};

  onRadioChange(radio: NgbRadio) {
    this.writeValue(radio.value);
    this.onChange(radio.value);
  }

  onRadiovalueUpdate() { this._updateradiosValue(); }

  register(radio: NgbRadio) { this._radios.add(radio); }

  registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }

  registerOnTouched(fn: () => any): void { this.onTouched = fn; }

  setdisabledState(isdisabled: boolean): void {
    this._disabled = isdisabled;
    this._updateradiosdisabled();
  }

  unregister(radio: NgbRadio) { this._radios.delete(radio); }

  writeValue(value) {
    this._value = value;
    this._updateradiosValue();
  }

  private _updateradiosValue() { this._radios.forEach((radio) => radio.updateValue(this._value)); }
  private _updateradiosdisabled() { this._radios.forEach((radio) => radio.updatedisabled()); }
}


/**
 * Marks an input of type "radio" as part of the NgbRadioGroup.
 */
@Directive({
  selector: '[ngbButton][type=radio]',host: {
    '[checked]': 'checked','[disabled]': 'disabled','[name]': 'nameAttr','(change)': 'onChange()','(focus)': 'focused = true','(blur)': 'focused = false'
  }
})
export class NgbRadio implements OnDestroy {
  private _checked: boolean;
  private _disabled: boolean;
  private _value: any = null;

  /**
   * The name of the input. All inputs of a group should have the same name. If not specified,* the name of the enclosing group is used.
   */
  @input() name: string;

  /**
   * You can specify model value of a given radio by binding to the value property.
   */
  @Input('value')
  set value(value: any) {
    this._value = value;
    const stringValue = value ? value.toString() : '';
    this._renderer.setProperty(this._element.nativeElement,'value',stringValue);
    this._group.onRadiovalueUpdate();
  }

  /**
   * A flag indicating if a given radio button is disabled.
   */
  @Input('disabled')
  set disabled(isdisabled: boolean) {
    this._disabled = isdisabled !== false;
    this.updatedisabled();
  }

  set focused(isFocused: boolean) {
    if (this._label) {
      this._label.focused = isFocused;
    }
  }

  get checked() { return this._checked; }

  get disabled() { return this._group.disabled || this._disabled; }

  get value() { return this._value; }

  get nameAttr() { return this.name || this._group.name; }

  constructor(
      private _group: NgbRadioGroup,private _label: NgbButtonLabel,private _renderer: Renderer2,private _element: ElementRef) {
    this._group.register(this);
  }

  ngOnDestroy() { this._group.unregister(this); }

  onChange() { this._group.onRadioChange(this); }

  updateValue(value) {
    this._checked = this.value === value;
    this._label.active = this._checked;
  }

  updatedisabled() { this._label.disabled = this.disabled; }
}

请注意

@Directive({
  selector: '[ngbButton][type=radio]','(blur)': 'focused = false'
  }
})

没有provider部分,但构造函数有一个NgbRadioGroup和NgbButtonLabel.此外,在使用指令时,不要像这样放弃ngbButtonLabel:

<div [(ngModel)]="model" ngbRadioGroup>
  <label>
    <input ngbButton type="radio" name="radio" [value]="values[0]"/> {{ values[0] }}
  </label>
</div>

导致NgbButtonLabel没有提供者!错误.我遗失了什么声明?以下是其完整存储库的链接:https://github.com/ng-bootstrap/ng-bootstrap

ng-bootstrap包期望该元素
<input ngbButton type="radio" ...>

在您提供NgbRadio指令的情况下,将提供您提供NgbButtonLabel指令的父元素.

所以你的模板应该是这样的:

<label ngbButtonLabel> <======== add ngbButtonLabel attribute
  <input ngbButton type="radio" name="radio" [value]="values[0]"/> {{ values[0] }}
</label>

要理解为什么会这样,你需要从层次结构树中知道how angular gets dependencies.

假设我们的根组件中有以下模板:

app.component.html

<div dirA>
  <comp-b dirB>
    <span dirC>
      <i dirD></i>
    </span>
  </comp-b>
</div>

以及以下指令集:

@Directive({
  selector: '[dirA]',providers: [{ provide: 'A',useValue: 'dirA provider' }]
})
export class DirA {}

@Component({
  selector: 'comp-b',template: '<ng-content></ng-content>',providers: [{ provide: 'B',useValue: 'comp-b provider'}]
})
export class ComponentB {}

@Directive({ selector: 'dirB' })
export class DirB {}

@Directive({ selector: 'dirC' })
export class DirC {}

@Directive({ selector: 'dirD' })
export class DirD {
  constructor(private dirB: DirB) {}
}

注意:私有dirB:DirB就像私有_label:NgbButtonLabel在你的情况下

Angular编译器为我们的模板创建视图工厂:

注意:我在组件上使用了新的preserveWhitespaces:false选项,因此我们在工厂中看不到textDef.

然后从这个工厂角度creates ViewDefinition并实例化主机元素的提供者.

角度编译器在哪里采用提供者?

你应该知道的主要事情是each directive provides its own token

所以这里的提供者看起来如下:

<div dirA>               [DirA]
  <comp-b dirB>          [ComponentB,DirB]
    <span dirC>          [DirC] 
      <i dirD></i>       [DirD]
    </span>
  </comp-b>
</div>

以下规则是我们在指令元数据中声明的提供程序(提供程序数组)也将添加到主机元素提供程序:

<div dirA>               [DirA,{ provide: 'A',useValue: 'dirA provider' }]
  <comp-b dirB>          [ComponentB,DirB,{ provide: 'B',useValue: 'comp-b provider'}]
    <span dirC>          [DirC] 
      <i dirD></i>       [DirD]
    </span>
  </comp-b>
</div>

现在angular正试图获得DirB指令的提供者

@Directive({ selector: 'dirD' })
export class DirD {
  constructor(private dirB: DirB) {}
}

角度依赖性解析机制以< i dirD>< / i>开头.节点并上升到< div dirA>:

null or throw error
                    /\
                 @NgModule
                    /\
                  my-app
<div dirA>          /\     [DirA,useValue: 'dirA provider' }]
  <comp-b dirB>     /\     [ComponentB,useValue: 'comp-b provider'}]
    <span dirC>     /\     [DirC]   
      <i dirD></i>  /\     [DirD]  
    </span>
  </comp-b>
</div>

因此,角度将在< comp-b dirB>上找到DirB提供者.主机元素.我们可能会认为angular会使DirB提供者BUT三步
确实是角度uses prototypical inheritance来定义元素的提供者.

这样我们的树看起来像:

null or throw error
                    /\
                 @NgModule
                    /\
                  my-app
<div dirA>          /\     [
                             DirA,useValue: 'dirA provider' }
                           ]
  <comp-b dirB>     /\     [
                             ComponentB,useValue: 'comp-b provider'},DirA,useValue: 'dirA provider' }
                           ]
    <span dirC>     /\     [
                             DirC,ComponentB,useValue: 'dirA provider' }
                           ]  
      <i dirD></i>  /\     [
                             DirD,DirC,useValue: 'dirA provider' }
                           ]  
    </span>
  </comp-b>
</div>

正如我们所看到的,实际上角度仅使用一步来从< i dirD>< / i>中找到DirB提供者.主机元素.

Angular 2在Bootstrap之前解析服务

Angular 2在Bootstrap之前解析服务

http://plnkr.co/edit/yhQQZxTxB8ZVFysqO6lP?p=preview

在AppComponent加载之前,如何确保我的AuthService得到解决?

//main entry point
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Http,HTTP_PROVIDERS} from '@angular/http';
import {App} from './app';
import {AuthService} from './auth.service';
import {provide,enableProdMode,APP_INITIALIZER} from '@angular/core';

bootstrap(App,[HTTP_PROVIDERS,provide("isLoggedIn",{ useFactory: (auth:AuthService) => () => auth.login(),deps:[HTTP_PROVIDERS],multi: true }),])
  .catch(err => console.error(err));

解决方法

您可以使用APP_INITIALIZER令牌来提供您的authFactory:

//main entry point
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Http,APP_INITIALIZER} from '@angular/core';

export function authFactory(auth: AuthService){
    return auth.login()
}

bootstrap(App,[
    HTTP_PROVIDERS,{
        provide: APP_INITIALIZER,useFactory: (auth),deps: [AuthService],multi: true
    }
]).catch(err => console.error(err));

Angular 学习系列 - - angular.bind、angular.bootstrap、angular.copy

Angular 学习系列 - - angular.bind、angular.bootstrap、angular.copy

高春辉、王春生、朱峰:关于开源创业的 15 件小事

angular.bind

返回一个调用 self 的函数 fn(self 代表 fn 里的 this). 可以给 fn 提供参数 args(*). 这个功能也被称为局部操作,以区别功能。

格式:angular.bind(self,fn,args);

self:object  对象; fn 的上下文对象,在 fn 中可以用 this 调用

fn:function; 绑定的方法

args:传入 fn 的参数

使用代码: 

var obj = { name"Any" };var fn = function (Adj{
      console.log(this.name + "is a boy!!! And he is " + Adj + " !!!");
   };var f = angular.bind(obj, fn, "handsome");
f();//Any is a boy!!! And he is handsome!!!var t = angular.bind(obj, fn);
t("ugly");// Any is a boy!!! And he is ugly!!!

bind 顾名思义绑定的意思,那么假如我们要把 A 绑到 B 上,那么必须又有绑定的东西和被绑定的东西。这里需要的就一个对象和一个函数。那么怎么绑?本兽的理解是把对象 “绑” 到函数的 this 上去执行,这时候 fn 的 this 就等于 obj 了,至于第三个参数,可有可无,看需求,如果函数需要传入参数,那么我们可以把 angular.bind 的第三个参数放上去,这就是传入 fn 函数的参数了。

案例中第一种写法是定义绑定的时候就把 fn 所需的参数传进去了,调用的时候直接用,而案例中第二种写法是先绑定,在调用执行的时候再给 fn 传参,效果是一样的...

angular.bootstrap

使用这个功能来手动启动 angular 应用。基于 ngScenario 的端对端测试不能使用 bootstrap 手动启动,需要使用 ngApp.

Angular 会检测应用在浏览器是否已启动并且只允许第一次的启动,随后的每次启动都将会导致浏览器控制台报错.

这可以防止应用出现多个 Angular 实例尝试在 Dom 上运行的一些奇异结果.

格式:angular.bootstrap(element,[modules]);

element:Dom 元素,angular 应用启动的根节点

modules:数组,angular 的应用程序模块

使用代码:

<div id="ngApp"> <div ng-controller="testCtrl as ctrl"> {{ctrl.value}}     </div>
  </div>

(function ({
      angular.module("Demo", [])
      .controller("testCtrl", testCtrl);      function testCtrl({          this.value = "Hello World";
      }
      angular.bootstrap(document.getElementById("ngApp"), ["Demo"]);
  }());

一般来说,我们写 ng 程序,都会在页面 Dom 元素上写 ngApp 指令用来启动 Angular 程序,但是也可能出现一些特殊情况需要我们在启动之前干些什么或者需要我们手动启动应用程序,这时候 angular.bootstrap 就派的上用场了。

angular.copy

针对对象或数字创建一个深层的拷贝。

格式:angular.copy(source, [destination]);

source:被拷贝的对象

destination:接收的对象 [注意:参数类型是对象或数组]

使用代码:

var objA, objD = []; //objA:undefined objD:[]var objB = { text: "Hello World" };var objC = {text:"Hai",value:"Test"};
objA = angular.copy(objB); // objA:text:"Hello World"objB:text:"Hello World"}angular.copy(objC, objD);// objC:{text: "Hai"value: "Test"objD:[text: "Hai"value: "Test"]

本兽对 Angular API 逐个的学习并且进行翻译,然后写能运行成功的代码,并把学习过程进行整理记录及分享... 

angular-cli创建angular2项目并添加ng2-bootstrap

angular-cli创建angular2项目并添加ng2-bootstrap

1、首先全局安装angular-cli,并创建项目

npm install -g angular-cli
ng new my-app
cd my-app

2、安装ng2-bootstrap和bootstrap

 npm install ng2-bootstrap bootstrap --save

3、在主模块中导入,需要的模块(src/app/app.module.ts)

import { AlertModule } from ''ng2-bootstrap'';
...

@NgModule({
   ...
   imports: [AlertModule.forRoot(), ... ],
    ... 
})

只要在模块总导入,不需要在组建中添加,很方便。

4、在angular-cli.json中配置样式文件

"styles": [
   "styles.css",
   "../node_modules/bootstrap/dist/css/bootstrap.min.css"
]

5、 在模板中调用 src/app/app.component.html

<alert type="success">hello</alert>

我们今天的关于angular2-routing – 如何在bootstrap动态提供路由?angular动态路由配置的分享就到这里,谢谢您的阅读,如果想了解更多关于Angular 2 – ng-bootstrap如何为其NgbRadio指令提供NgbRadioGroup和NgbButtonLabel?、Angular 2在Bootstrap之前解析服务、Angular 学习系列 - - angular.bind、angular.bootstrap、angular.copy、angular-cli创建angular2项目并添加ng2-bootstrap的相关信息,可以在本站进行搜索。

本文标签: