2016-07-08 84 views
0

我已經創建了服務的本地instance並直接從中訪問數據。如果它是一個簡單的用例(在組件之間共享數據),這是不正確的。我想了解一些ng2的核心概念,我覺得可能有更好的選擇。Angular 2 - 在服務中訪問數據的正確方法是什麼?

export class FormTwoComponent implements OnInit { 
    private model: WinnerModel; 

    constructor(private formService: FormService, private router: Router) {} 

    ngOnInit() { 
     this.model = this.formService.winnerModel; 
    } 

    onSubmit() { 
     this.formService.winnerModel = this.model; 
     this.router.navigate(['/form/3']) 
    } 
} 

感謝

+0

你能否詳細說明你的問題?你想訪問一個服務的數據到另一個服務,或者你想要它訪問控制器?兩者都有自己獨立的數據傳輸方式。 –

回答

0

角有大約component interactions一個美好的一頁。我覺得有一件事情沒有太明確的是,如果你沒有引用對象,那麼你的組件中的數據將被拋在後面。例如:

component.variable = service.variable //this will take the current value of what the service variable is, if the service variable ever changes then the component will not get updated. 
component.object = service.object //this will however create a link and any updates or changes made to the service object, then the component reference will be notified and updated. 
相關問題