Angular 2/Ionic 2 ngModel 动态全局变量

Angular 2/Ionic 2 ngModel Dynamic Global Variable

大家好,我目前正在尝试全局使用我的 ngModeled 变量。

到目前为止,我有以下代码片段。

homepage.html

<ion-input type="text" value="" [(ngModel)]="databaseID"> 

homepage.ts

public databaseID;

这些函数有效,当我尝试从 home.ts class 打印 ngModeled 数据时,它会打印用户输入的内容。但是我不确定如何从另一个 class 调用 databaseID。我已经尝试将 databaseID 设置为全局(全局是静态的,因此这将不起作用)。

你能解释一下我可以从不同的 class 访问这个变量的方法吗?

我的一些可能想法是依赖注入和使用提供程序。但我不确定这样做的最佳方式是什么。

在不同 components/directives 之间共享变量的最佳方式是使用服务。您可以做的是将 ngModel 直接绑定到一个服务,然后从多个组件访问该服务。

服务:

@Injectable()
export class MyService {
    databaseId: string;

    constructor() {
        this.databaseId = "1234";
    }
}

组件:

export class MyComponent {
    constructor(private myService: MyService) { }
}

HTML:

<ion-input type="text" value="" [(ngModel)]="myService.databaseID">

服务教程:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

依赖注入:https://angular.io/docs/ts/latest/cookbook/dependency-injection.html

I am not sure how to call databaseID from another class

其他 类 是否需要在 databaseID 更改时执行某些逻辑?如果是这样,请在服务中使用 Observable 或 Subject。另一个 类 将 subscribe() 通知 Observable 发生变化。有关示例,请参见 https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service。 (尽管这是使用服务在父子之间进行通信的示例,但相同的技术适用于任何两个组件之间的通信。)

如果你不需要执行任何逻辑,那么@Brandyn 提供的答案就很好。但是,我不会直接在组件的 view/template 中使用服务 属性 名称。相反,我会使用组件 属性 或 "get" accessor:

@Component({
   template: `<ion-input type="text" [(ngModel)]="database.id">`
})
export class HomePageComponent {
    constructor(private _dbService: DatabaseService) { }
    get database() { return this._dbService.database; }
}
export class DatabaseService {
    database: { id: 0 }; 
}

您可能希望为数据库类型定义一个接口,如果它具有许多属性:

export interface Database {
    id: number;
    // other properties here
}

然后

get database(): Database { return this._dbService.database; }