簡體   English   中英

Angular-組件之間的共享服務不起作用

[英]Angular - shared service between components doesn't work

我有一個聲明變量的服務。 在我的組件中,我使用此變量將數據放入其中。

服務:

@Injectable()
export class DataService {

    public msgs = [];

    constructor() { }       

}

現在,我在組件中使用此變量:

export class MessagesComponent implements OnInit {   

    constructor(private dataService: DataService){}

    ngOnInit() {   
        this.getData();   
    }

    getData(){
        let msgs = [];

        if (diffr <= this.geomessage[i].range) {
            this.geomessage[i].dist = diffr;
            msgs.push(this.geomessage[i]);
            //console.log("this message: ", this.geomessage[i]); //DEBUG
        }
        this.dataService.msgs = msgs;

    }    
}    

我只發布了必要的代碼this.dataService.msgs充滿了消息,效果很好。 當我轉到另一個組件時,this.dataService.msgs的數據仍然存在,但是當我回到Messagescomponentthis.dataService.msgsundefined直到我再次填充它,但我需要其中的數據。 有人知道該怎么做嗎?

謝謝

如果要在@Component批注的providers數組內提供DataService

@Component({
    ...
    providers: [DataService],
})...

該服務將為此組件提供一個單例(它將創建一個新實例)(如果它們也未在其注釋下提供此服務,則為子項)。

如果要在多個組件之間使用此服務並共享該服務的同一實例,請執行以下操作: 您需要在組件/模塊中提供此服務,該組件/模塊是DI樹中這些組件的父級。 如果這是全局服務,建議您在AppModule(或共享模塊)中提供。

@NgModule({
    providers:[DataService]
})

資料來源: https : //angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances

關於echonax答復的簡短說明是,提供者是按層次結構工作的。 如果將其添加到應用程序模塊中,它將在整個應用程序中正常工作,因此不應在其他任何地方“提供”它。 但是,如果不需要“全局”服務,則只需在父組件上提供即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM