繁体   English   中英

Aurelia打字稿和DI

[英]Aurelia Typescript and DI

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

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>

的start.html

<template>
<h1>Start</h1>

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

好吧,所以上面应该很简单,我有主应用程序,start.html只是一个路由,将在路由器视图中启动时加载。 正如所料,App和Start First Name绑定最初都显示为John。 但是,当我单击执行http get调用的updateApplicant委托时,只有App First Name绑定更新到Mike,我期望Start视图的申请人也会更新,因为他们应该引用相同的Applicant对象, ? 我对Aurelia相当新,不确定我是否正在做DI以注入申请人在不同视图中使用的方式是正确的方式,我期待申请人对象是单身人士并想要注入不同的视图在申请中。 我最初认为这是一个词汇范围界定问题,但这意味着什么都不应该更新。

行为

不,你不是。 由于JS变量只是对内存中对象的引用,因此您的变量applicant者只是一个引用,当您在函数updateApplican更改它时,您只需更改对内存中另一个对象的引用。 这意味着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
          });
  }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM