无法使用Angular服务在两个角度4组件之间传递数据

时间:2017-08-02 13:43:41

标签: angular components angular-services

无法使用服务将数据从一个角度组件传递到另一个角度组件。这是服务代码:

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  public serviceData: string;
}

以下是组件home

import {Component, OnInit, Input} from '@angular/core';
import {Router} from "@angular/router";
import { DataService } from '../common/common.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  constructor(public router: Router, public commonService: DataService) {
    this.commonService.serviceData = 'Message from Home Component to App Component!';
    this.router.navigate(["overview"]);
  }

}

以下是概述组件:

import {Component, OnInit, Input} from '@angular/core';
import { DataService } from '../common/common.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.css']
})
export class OverviewComponent {
  constructor(public messageService: DataService) {
    alert(this.messageService.serviceData);
  }
}

OverviewComponent中的提醒始终显示undefined

2 个答案:

答案 0 :(得分:2)

由于您已在组件级别注入DataService提供程序,因此实例将从当前组件共享到后代注入器树。因此,在这种情况下,您有DataService app-home& app-overview会有所不同,换句话说,Angular会为DataService创建两个不同的实例。

建议的做法是在根模块providers元数据选项上注册可共享数据提供程序,以便每个使用者都可以访问同一个实例。确保从组件级DataService元数据选项中删除providers

@NgModule({
  imports: [..],
  declarations: [AppComponent, ...],
  providers: [DataService, ...], //<- moved here
  bootstrap: [AppComponent]
})
export class AppModule {

}

答案 1 :(得分:0)

我建议你使用rxjs主题。像你一样在你的服务中创建新的rxjs主题

import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {

    myNewSubject = new Subject<any>();

    informDataChanges(passyourobject){
      this.myNewSubject.next(passyourobject);
  }

}

当您的组件发生更改或者您想将数据传递到另一个组件时,只需从组件中调用此服务函数,并将数据作为参数传递给此函数。你可以用这样的东西做到这一点

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-some',
      templateUrl: './some.component.html',
      styleUrls: ['./some.component.css']
    })
    export class SomeComponent implements OnInit {

      constructor( private myService: MyService) { }

      someFunction(){
        this.myService.informLogout('somedata');//Passing data to service here
      }

  ngOnInit() {

  }

}

现在您需要做的就是在另一个组件中订阅该数据。重要主题会随时监视对其的任何更改,数据将是连续流,并将自动订阅。因此,最好在构造函数中订阅主题,并且更改将立即反映在该组件中。

你这样做的事情

import { Component, OnInit } from '@angular/core';

        @Component({
          selector: 'app-another',
          templateUrl: './another.component.html',
          styleUrls: ['./another.component.css']
        })
        export class AnotherComponent implements OnInit {

          constructor( private myService: MyService) {
            this.myService.myNewSubject.subscribe(data=>{
             console.log(data);
       }) 
}

这样,您可以轻松地在任意数量的组件之间传递数据。