2017-02-14 40 views
1

我在写一个简单的服务来设置和获取对象的值。代码将值发送给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()的或后()来更新的位置。

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'); 
    } 
} 

真的很感谢您的时间来通过这个!

+0

不确定这是否是拼写错误,但它在我看来就像调用了不存在的方法。您可以调用'this.nav.setLocation('start','about','family')',但该方法仅针对两个输入参数定义。 –

+0

@alex,我试图简化代码,并有可能通过一些清理遗漏。 – iMad

回答

3

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

@NgModule({ 
    /* ... */ 
    providers: [ 
     NavService 
    ] 
    /* ... */ 
}) 
export class AppModule { 
} 
+0

这可能是问题所在。我在顶层和子组件中导入服务,并分别在每个组件中声明它们。什么是导入和声明服务的正确方式? – iMad

+0

在每个组件中导入服务是可以的,但它可能只能在应用程序模块中“提供”(使用'providers:[]'声明)一次。 – admax

+0

就是这样。以艰难的方式了解提供商。谢谢! – iMad