Angular - 组件之间的共享服务不起作用 [英] Angular - shared service between components doesn't work

查看:43
本文介绍了Angular - 组件之间的共享服务不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项声明变量的服务.在我的组件中,我使用这个变量将数据放入其中.

I have a service where I declare my variable. In my component I use this variable to put data into it.

服务:

@Injectable()
export class DataService {

    public msgs = [];

    constructor() { }       

}

现在我在我的组件中使用这个变量:

Now I use this variable in my component:

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 het 充满了消息,这工作正常.当我到达另一个组件时,this.dataService.msgs 的数据仍然存在,但是当我回到 Messagescomponent 时,this.dataService.msgsundefined 直到我再次填充它,但我需要其中的数据.有人知道怎么做吗?

I have only posted the necessary code.The this.dataService.msgs het filled with messages this works fine. When I got to another component the data of this.dataService.msgs still exists but when i Get back tot the Messagescomponent the this.dataService.msgs is undefined till i fill it again but I need the data that was in it. Does somebody know how to do this?

谢谢

推荐答案

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

If you are providing your DataService inside the providers array of your @Component annotation,

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

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

this service will be a singleton (it will create a new instance) for this component (and it's children if they have not provided this service under their annotation also).

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

If you want to use this service among multiple components and share the same instance of the service; you need to provide this service in a component/module which is the parent of these components in the DI tree. If this is a global service I suggest providing it only in your AppModule (or in a shared module).

@NgModule({
    providers:[DataService]
})

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

全球级服务现在定义为

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

这应该是推荐的方法,因为如果不使用它会自行摇一摇.

This should be the recommended approach since it will tree-shake itself if it's unused.

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

这篇关于Angular - 组件之间的共享服务不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆