Angular 2 共享数据服务不工作 [英] Angular 2 Shared Data Service is not working

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

问题描述

我已经构建了一个共享数据服务,旨在保存用户登录详细信息,然后可用于在标题上显示用户名,但我无法让它工作.

I have built a shared data service that's designed to hold the users login details which can then be used to display the username on the header, but I cant get it to work.

这是我的(缩写)代码:

Here's my (abbreviated) code:

// Shared Service
@Injectable()
export class SharedDataService {

    // Observable string source
    private dataSource = new Subject<any>();

    // Observable string stream
    data$ = this.dataSource.asObservable();

    // Service message commands
    insertData(data: Object) {
        this.dataSource.next(data)
    }
}

...

// Login component
import { SharedDataService } from 'shared-data.service';
@Component({
    providers: [SharedDataService]
})
export class loginComponent {
    constructor(private sharedData: SharedDataService) {}

    onLoginSubmit() {
        // Login stuff
        this.authService.login(loginInfo).subscribe(data => {
             this.sharedData.insertData({'name':'TEST'});
        }
    }
}

...

// Header component
import { SharedDataService } from 'shared-data.service';
@Component({
    providers: [SharedDataService]
})
export class headerComponent implements OnInit {
    greeting: string;

    constructor(private sharedData: SharedDataService) {}

    ngOnInit() {
        this.sharedData.data$.subscribe(data => {
            console.log('onInit',data)
            this.greeting = data.name
        });
    }
}

我可以在服务 insertData() 方法中添加一个控制台日志,它支持正在更新的模型,但 OnInit 方法不反映更改.

I can add a console log in the service insertData() method which shoes the model being updated, but the OnInit method doesn't reflect the change.

我编写的代码深受这个 plunkr 的启发工作,所以我不知道出了什么问题.

The code I've written is very much inspired by this plunkr which does work, so I am at a loss as to what's wrong.

在这里发帖之前,我尝试了其他一些尝试.这个这个 同样适用于演示,但不适用于我的应用.

Before posting here I tried a few other attempts. This one and this one again both work on the demo, but not in my app.

我使用的是 Angular 2.4.8.

I'm using Angular 2.4.8.

查看不同的教程和论坛帖子都展示了如何使共享服务正常工作的类似示例,所以我想我做错了什么.我刚开始使用来自 AngularJS 背景的 Angular 2 进行构建,这是让我真正陷入困境的第一件事.

Looking through different tutorials and forum posts all show similar examples of how to get a shared service working, so I guess I am doing something wrong. I'm fairly new to building with Angular 2 coming from an AngularJS background and this is the first thing that has me truly stuck.

谢谢

推荐答案

这似乎是理解 Angular 的依赖注入时反复出现的问题.

This seems to be a recurring problem in understanding Angular's dependency injection.

基本问题在于您如何配置服务提供者.

The basic issue is in how you are configuring the providers of your service.

简短版本:始终在 NgModule 级别配置您的提供程序除非您需要一个特定组件的单独实例.只有这样,您才能将其添加到您想要单独实例的组件的 providers 数组中.

The short version: Always configure your providers at the NgModule level UNLESS you want a separate instance for a specific component. Only then do you add it to the providers array of the component that you want the separate instance of.

长版:Angular 的新依赖注入系统允许您拥有多个服务实例(这与 AngularJS 形成对比,即 Angular 1 只允许单例).如果您在 NgModule 级别为您的服务配置提供程序,您将获得一个由所有组件/服务等共享的服务的单例.但是,如果您将一个组件配置为也有一个提供程序,那么该组件(和它的所有子组件)将获得它们都可以共享的服务的不同实例.如果您需要,此选项允许使用一些强大的选项.

The long version: Angular's new dependency injection system allows for you to have multiple instances of services if you so which (which is in contrast to AngularJS i.e. Angular 1 which ONLY allowed singletons). If you configure the provider for your service at the NgModule level, you'll get a singleton of your service that is shared by all components/services etc. But, if you configure a component to also have a provider, then that component (and all its subcomponents) will get a different instance of the service that they can all share. This option allows for some powerful options if you so require.

这是基本模型.当然,它并不是那么简单,但是默认情况下在 NgModule 级别配置提供程序的基本规则,除非您明确希望特定组件有不同的实例,否则您会走得很远.

That's the basic model. It, is of course, not quite so simple, but that basic rule of configuring your providers at the NgModule level by default unless you explicitly want a different instance for a specific component will carry you far.

如果您想深入了解,查看官方 Angular 文档

另请注意,延迟加载也使这条基本规则复杂化,因此再次检查文档.

Also note that lazy loading complicates this basic rule as well, so again, check the docs.

所以对于您的具体情况,

So for your specific situation,

@Component({
    providers: [SharedDataService]  <--- remove this line from both of your components, and add that line to your NgModule configuration instead
})

这篇关于Angular 2 共享数据服务不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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