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;

    }    
}    

我只发布了必要的 code.The this.dataService.msgs,其中充满了消息,效果很好。当我到达另一个组件时 this.dataService.msgs 的数据仍然存在但是当我回到 Messagescomponentthis.dataService.msgsundefined 直到我再次填充它但我需要数据那是在里面。有人知道怎么做吗?

感谢

如果您在 @Component 注释的提供者数组中提供 DataService

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

此服务将是此组件的单例(它将创建一个新实例)(如果他们也没有在其注释下提供此服务,则它是子组件)。

如果您想在多个组件之间使用该服务并共享同一个服务实例;您需要在 component/module 中提供此服务,它是 DI 树中这些组件的父级。如果这是一项全球服务,我建议在您的 AppModule(或共享模块)中提供它。

@NgModule({
    providers:[DataService]
})

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

Angular 9 次更新

全球级服务现在定义为

@Injectable({
  providedIn: 'root',
})
export class DataService {

这应该是推荐的方法,因为如果未使用它会自行摇树。

来源:https://angular.io/guide/providers#providedin-and-ngmodules

关于 echonax 的回复的快速说明是,提供者按层次结构工作。如果您将它添加到应用程序模块,它将在整个应用程序中工作,因此您不应该 'provide' 它在其他任何地方。 但是,如果不需要服务 'globally',只需在父组件上提供即可。