-1

我从 angular 2 开始我有几个问题

在角度,我曾经在路由配置中定义一个变量,并基于该变量我在 app.run() 中编写了一个代码,它将检查该变量是否为真,是否应该发生某些事情。因此,它所做的就是在更改路由器时检查该条件。

现在,如果我想在 Angular 2 中实现相同的效果怎么办。我们没有 app.run() 而是我们有引导程序,是否可以在路由器配置中定义用户定义的变量?

我尝试搜索,但找不到我的问题的答案。请让我知道是否需要对我提出的问题进行任何澄清。

谢谢

4

1 回答 1

1

当在 angular2 中加载组件时,将调用生命周期 OnInit - 如果您想在加载新组件时从用户定义的配置中检查某些内容,您可以在其中编写代码,例如:

import { Component, OnInit } from '@angular/core'

@Component({
    ...
})
export class MyComponent implements OnInit {

    ngOnInit() {
        // write the check for the config value in here
    }
}

您唯一需要做的另一件事是导入其中包含用户定义配置的任何文件,并在您定义的每个组件的 ngOnInit 方法中使用该文件。

另一种方法是订阅 angular 导出的位置服务,每次位置 url 更改时运行检查。为避免重复订阅,您需要将此代码放在主 AppComponent 文件中。您唯一需要做的另一件事是拥有一个全局服务,您可以将其导入到所有组件中,该服务包含某种标志,可以告诉您您的配置值是否设置为某个值。

import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'

... METADATA ...

export class AppComponent implements OnInit {

    constructor(private location: Location) {}

    ngOnInit() {
        this.location.subscribe((value) => {
            // do check in here / set value inside global service
        });
    }
于 2016-08-23T15:41:04.487 回答