角度服务不会更新对象的值

时间:2017-02-14 07:52:56

标签: angular typescript

我正在编写一个简单的服务来设置和获取对象的值。代码将值发送给setter,但下次我获取代码时,值仍然相同。你能不能看看代码并告诉我我错过了什么? (我没有包含所有组件标题和导入以保持此简短。)

//service.ts
export class NavService {

   private location;

   constructor(){

       this.location = {
          next:'',
          back: ''
       }
   }
   setLocation(back:string, next:string){
      this.location.next = next;
      this.location.back = back;
   }

   getLocation(){

     return this.location
   }

}

在我看来,我有一个调用next()或back()的按钮来更新位置。

export class PlanComponent {

   location;
   currentPage : string = 'start';


   constructor(private nav:NavService){}

  forward(){
     this.location = this.nav.getLocation();
     this.currentPage = this.location.next;

   }

 }

新位置正在加载新组件。新组件假设设置新位置。但是在父组件中,当我尝试获取位置时,我得到了相同的旧值。

 export class AboutComponent {

    constructor(private nav: NavService){
       this.nav.setLocation('start', 'about');
   }
 }

非常感谢您抽出时间!

1 个答案:

答案 0 :(得分:3)

可能是因为NavService生命周期,您的组件可能会在每个组件创建时获得服务的新实例。确保在顶级组件或模块上提供NavService

@NgModule({
    /* ... */
    providers: [
        NavService
    ]
    /* ... */
})
export class AppModule {
}
相关问题