Angular 2共享数据服务无法正常工作 [英] Angular 2 Shared Data Service is not working

查看:101
本文介绍了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.

查看不同的教程和论坛帖子都显示了如何使共享服务正常工作的类似示例,所以我想我做错了什么。我很擅长使用AngularJ来构建AngularJS背景,这是让我真正陷入困境的第一件事。

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天全站免登陆