2017-08-02 28 views
1

無法使用服務將數據從一個角度組件傳遞到另一個角度組件。下面是服務代碼:無法使用角度服務在兩個角度4組件之間傳遞數據

import { Injectable } from '@angular/core'; 

@Injectable() 
export class DataService { 
    public serviceData: string; 
} 

下面是部分home

import {Component, OnInit, Input} from '@angular/core'; 
import {Router} from "@angular/router"; 
import { DataService } from '../common/common.service'; 

@Component({ 
    selector: 'app-home', 
    templateUrl: './home.component.html', 
    styleUrls: ['./home.component.css'] 
}) 
export class HomeComponent { 

    constructor(public router: Router, public commonService: DataService) { 
    this.commonService.serviceData = 'Message from Home Component to App Component!'; 
    this.router.navigate(["overview"]); 
    } 

} 

這裏是概述部分:

import {Component, OnInit, Input} from '@angular/core'; 
import { DataService } from '../common/common.service'; 
import { Subscription } from 'rxjs/Subscription'; 

@Component({ 
    selector: 'app-overview', 
    templateUrl: './overview.component.html', 
    styleUrls: ['./overview.component.css'] 
}) 
export class OverviewComponent { 
    constructor(public messageService: DataService) { 
    alert(this.messageService.serviceData); 
    } 
} 

OverviewComponent警報總是顯示undefined

+0

有一個在[DOC]一堆例子(https://stackoverflow.com/documentation/angular/10836/sharing-data-among-components#t=201708021351339613133) – Nehal

+0

的可能的複製[如何分享組件之間的數據使用正確的服務?](https://stackoverflow.com/questions/40468172/how-to-share-data-between-components-using-a-service-properly) –

+0

服務是爲了單例,這是一個類的單個實例。由於它是單身人士,它可以保留一組任何數據並跨組件共享。爲了確保一個服務是一個單身人士,它只能一次註冊。您通過將它添加到兩個組件的[[providers]數組中來註冊它兩次。推薦的方法是註冊它與應用程序模塊,如下所示:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/ – DeborahK

回答

2

由於您已在組件級別注入DataService提供程序,該實例將從當前組件共享到後代注入器樹。因此,在這種情況下,您有DataService實例app-home & app-overview將會有所不同,換句話說,Angular會爲DataService創建兩個不同的實例。

建議的做法是在根模塊providers元數據選項上註冊可共享數據提供程序,以便每個使用者都將訪問同一個實例。確保從組件級providers元數據選項中刪除DataService

@NgModule({ 
    imports: [..], 
    declarations: [AppComponent, ...], 
    providers: [DataService, ...], //<- moved here 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 

} 
+0

嘗試相同,但仍然無法傳遞數據。它顯示undefined – iJade

+0

你是否按照上面的答案並從兩個組件中刪除「提供者:[DataService]」? –

+0

@DeanChalk是的,我確實從組件 – iJade

相關問題