Angular2数据服务组件未接收其他组件上的值

Angular2数据服务组件未接收其他组件上的值,angular,angular2-services,Angular,Angular2 Services,目前,我正在使用共享服务将数据从一个组件传递到另一个组件。我在第一个组件上设置了值,并尝试在另一端检索值,但我收到的是空数组。下面是我的代码: **Ist Compnent:** @Component({ templateUrl: './landingPage.component.html', styleUrls: ['./landingPage.component.css'], providers: [LandingServic

目前,我正在使用共享服务将数据从一个组件传递到另一个组件。我在第一个组件上设置了值,并尝试在另一端检索值,但我收到的是空数组。下面是我的代码:

**Ist Compnent:**

        @Component({
        templateUrl: './landingPage.component.html',
        styleUrls: ['./landingPage.component.css'],
        providers: [LandingService],

    })

    export class LandingPageComponent {
        constructor(private landingService:LandingService) {

        }
     @Input() Location:string;
        @Input() Type:string;

        search(){
            //setting value in landing service
            this.landingService.SearchData[0]=this.Location;
            this.landingService.SearchData[1]=this.Type;
            console.log(this.landingService.SearchData) ///this print the data succesfully but when try to access on
// 2nd compnent receive and empty arrat

            }
第二部分

着陆服务


另外,我使用getter和setter进行了检查,但仍然面临相同的问题。当我设置数据时,任何人都可以告诉我我做错了什么,console打印了我希望在第二个组件上接收的正确数据,但以一个空数组结束。

您的提供程序不是单例。您在每个组件中分别提供服务,因此它们具有该服务的单独实例

如果组件在同一模块中。在modules@NgModule providers内提供服务。如果没有,则创建共享服务/模块

示例:

您已将两个组件中的LandingService设置为提供者。因此,它不是一个单一服务。您应该在app.module.ts中提供它


这个问题与您在组件中使用“提供者”选项有关

简短版本:

从两个单独的组件装饰器中删除providers选项,并将其添加到包含这些组件的NgModule或AppModule中

更新您的NGO模块:

@NgModule({
   imports: ...
   declarations: ....
   providers: [LandingService],   /// <- add this
})
export class ......
更新您的组件:

@Component({
    templateUrl: './landingPage.component.html',
    styleUrls: ['./landingPage.component.css'],
     ///providers: [LandingService],    // <-- remove this from BOTH components

 })
长版本:

当您向组件的providers数组中添加服务时,您基本上是在对Angular说,我希望该组件及其子组件有一个新的服务实例。因此,在您的示例中,您基本上告诉Angular您需要两个不同的LandingService类型的对象,每个组件一个。由于它们是两个不同的实例/对象,因此它们都有自己的数据


在Ngmodule中查看了解更多信息

,我将服务组件放置在导出或导入中?在提供中..提供阵列基本上必须在Ngmodule中设置。如果您需要在Ngmodule中设置SingleTon,请将LandingService添加到Ngmodule的提供商列表中。我会更新答案给你看当然,很乐意帮忙
@NgModule({
  //declarations,imports etc
  providers: [LandingService]
})
export class AppModule { }
@NgModule({
   imports: ...
   declarations: ....
   providers: [LandingService],   /// <- add this
})
export class ......
@Component({
    templateUrl: './landingPage.component.html',
    styleUrls: ['./landingPage.component.css'],
     ///providers: [LandingService],    // <-- remove this from BOTH components

 })