簡體   English   中英

在angular 6組件html中全局訪問js對象

[英]Access js object globally in angular 6 components html

我正在使用Angular6。我有一個內容為somefile.js的文件:

SomeObject = {
    value1: "Some value",
    value2: "Some value2"
}

我有多個組件,我想在任何組件html中訪問此文件/對象的這些值。

例如,在我的組件.html文件中,我想像這樣訪問該文件:

<div>
 {{ SomeObject.value1 }}
</div>

我怎樣才能實現這樣的目標?

您的模板只能看到在組件上公開的內容。 這意味着您需要在組件上創建一個公共字段,然后將對象分配給該字段。

import { SomeObject } from './path/to/some/object';

@Component({
// ...
})
export class FooComponent {
    SomeObject = SomeObject;
}

如果您在許多地方都需要該對象,則可以定義一個裝飾器來為您完成此任務。

定義裝飾器:

import { SomeObject } from './path/to/some/object';

export function SomeObjectDecorator(): Function {
    return (constructor: Function) => {
        constructor.prototype.SomeObject = SomeObject;
    }
}

將其應用於組件

import { SomeObjectDecorator } from './path/to/some/object/decorator';

@Component({
// ...
})
@SomeObjectDecorator()
export class FooComponent {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM