【问题标题】:Aurelia Typescript and DIAurelia 打字稿和 DI
【发布时间】:2015-09-26 09:45:52
【问题描述】:

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

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 视图的申请者也会更新,因为它们应该引用相同的申请者对象,对?我对 Aurelia 还很陌生,不确定我做 DI 注入申请人以在不同视图中使用的方式是否正确,我希望申请人对象是单例并希望注入不同的视图在应用程序中。我最初认为这是一个 ts 词法范围问题,但这意味着什么都不应该更新。

【问题讨论】:

    标签: typescript aurelia


    【解决方案1】:

    行为

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

    在这种情况下,两个视图都会发生变化,因为它仍然引用同一个包装对象

    【讨论】:

    • 这个是对的,我就不改了。我会说,由于申请人是它自己的类,这里的最佳实践是拥有一个申请人.update 方法并利用它来代替。
    • 我与 aurelia 没有任何交易,我的回答基于完全了解 DI 的工作原理
    • 感谢奥列格和马修!我应该已经意识到了,解决问题的好建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2016-09-17
    • 1970-01-01
    • 2018-12-25
    • 2021-08-08
    • 2016-02-06
    • 2014-01-23
    相关资源
    最近更新 更多