Aurelia Typescript and DI -


i running issue expect object(applicant in example) reference same, not getting expected behavior in example, great if can point me in right direction.

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 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> 

okay, above should pretty simple, have main app, start.html route loaded on start in router-view. expected, both app , start first name binding shows john. however, when click updateapplicant delegate executes http call, app first name binding updated mike, i'm expecting start view's applicant updated well, since should referencing same applicant object, right? i'm new aurelia, not sure if way i'm doing di inject applicant use in different views right way, i'm expecting applicant object singleton , want inject different views in application. thought ts lexical scoping issue, mean nothing should updated.

behavior

no, not. since js variables references objects in memory, variable applicant reference, , when change in function updateapplican change reference another object in memory. mean reference in start view still refering old one.

solution

there 1 trick. can store aplicant in wrapper. looks below

 //make singleton  class aplicantwrapper {        aplicant: aplicant;  } 

and inject views

@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 mike           });   } 

in case both view expect changes because still refering same wrapper object


Comments