Typescript Aurelia字体和DI

Typescript Aurelia字体和DI,typescript,aurelia,Typescript,Aurelia,我遇到了一个问题,我希望对象(示例中的申请人)引用是相同的,但是在这个示例中没有得到预期的行为,如果有人能为我指出正确的方向,那就太好了 app.ts: @inject(HttpClient, Applicant) export class App { applicant: Applicant; http: HttpClient; router: Router; constructor(httpClient, applicant) { this.

我遇到了一个问题,我希望对象(示例中的申请人)引用是相同的,但是在这个示例中没有得到预期的行为,如果有人能为我指出正确的方向,那就太好了

app.ts:

@inject(HttpClient, Applicant)
export class App {
    applicant: Applicant;
    http: HttpClient;
    router: Router;

    constructor(httpClient, applicant) {
        this.applicant = applicant;
        this.http = httpClient;
        this.applicant.firstName = "John";
    }
//router config code..
updateApplicant() {
    this.http.get("/fakeApplicant.json")
        .then(response => {
            this.applicant = response.content; //Sets first name to Mike
        });
}
start.ts

@inject(Applicant)
export class start {
    router: Router;
    applicant: Applicant;

    constructor(applicant : Applicant) {
        this.applicant = applicant;
    }
app.html

<template>
<div class="container">
    <div class="appHost">
        <router-view></router-view>
    </div>

    <button click.delegate="updateApplicant()">Update First Name</button>

    <h3>App First Name: ${applicant.firstName}</h3>
</div>

更新名字
应用程序名:${applicator.firstName}

start.html

<template>
<h1>Start</h1>

<h3>Start First Name: ${applicant.firstName}</h3>
</template>

开始
起始名字:${applicator.firstName}

好的,上面应该很简单,我有一个主应用程序,start.html只是一个路由,它将在路由器视图中的start上加载。正如所料,App和Start First Name绑定最初都显示为John。但是,当我单击执行http get调用的UpdateApplicationDelegate时,只有App First Name绑定被更新为Mike,我希望开始视图的申请者也被更新,因为它们应该引用相同的申请者对象,对吗?我是Aurelia的新手,不确定我注入申请人在不同视图中使用的DI方法是否正确,我希望申请人对象是一个单例对象,并希望在应用程序中注入不同的视图。我最初认为这是一个ts词汇范围问题,但这意味着什么都不应该更新

行为 不,你不是。因为JS变量只是对内存中对象的引用,所以变量
applicator
只是一个引用,当您在函数
updateapplian
中更改它时,您只需将引用更改为内存中的另一个对象。这意味着
start
视图中的引用仍然是引用旧的

解决方案 有一个诀窍。您可以将
Aplicant
存储在包装器中。它将是如下所示

 //make it also singleton
 class AplicantWrapper {
       aplicant: Aplicant;
 }
然后将其注入到您的视图中

@inject(HttpClient, ApplicantWrapper)
export class App {
applicantWraper: ApplicantWrapper;
http: HttpClient;
router: Router;

constructor(httpClient, applicant) {
    this.applicantWraper = applicant;
    this.http = httpClient;
    this.applicant.firstName = "John";
}
   //router config code..
 updateApplicant() {
      this.http.get("/fakeApplicant.json")
          .then(response => {
                this.applicantWrapper.applicant = response.content; //Sets first name to Mike
          });
  }

在这种情况下,这两个视图都希望更改,因为它仍然引用同一个包装器对象

这是正确的,所以我不会更改它。我会说,既然申请者是自己的班级,这里的最佳实践是有一个申请者。更新方法并利用它。我与aurelia没有交易,我的答案是基于完全了解DI的工作原理感谢Oleg和Matthew!我应该意识到,伟大的建议解决了这个问题!