共享服务无法将数据传递给下一个组件



我创建了两个组件和一个共享服务,我想要将数据从一个组件传递到另一个组件,但是我得到了空的对象Bellow是第一组件

import { Component, OnInit } from '@angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '@angular/router';

    @Component({
      selector: 'app-cone',
      templateUrl: './cone.component.html',
      styleUrls: ['./cone.component.css'],
      providers: [SharedService]
    })
    export class ConeComponent implements OnInit {
    req = <any>{};
      constructor(public service:SharedService,private router:Router) { }
       send(){
        this.req.fname= "ketan";
        this.req.lname= "pradhan";
        this.service.saveData(this.req); 
        console.log('str');
        this.router.navigate(['/apps/ctwo']);
      }
      ngOnInit() {
      }
    }

bellow是我需要从第一个分子传递数据的第二个组件,我得到空的对象是this.myname

import { Component, OnInit } from '@angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '@angular/router';
@Component({
  selector: 'app-ctwo',
  templateUrl: './ctwo.component.html',
  styleUrls: ['./ctwo.component.css'],
  providers: [SharedService]
})
export class CtwoComponent implements OnInit {
myName= <any>{};
  constructor(public service:SharedService,private router:Router) {
    this.myName=this.service.getData();
        console.log(this.myName);
   }
  ngOnInit() {
  }
}

Bellow是共享服务,用于在2个组件之间进行交流

import {组件,注射,输入,输出,eventEmitter}来自'@angular/core'

//名称服务导出接口mydata { 名称:字符串, lname:字符串}

@Injectable()
export class SharedService {
  sharingData: myData=<any>{};
  saveData(str){
    console.log('save data function called' + str.fname);
    console.log(this.sharingData);
    this.sharingData = str; 
    // this.sharingData.lname=str.lname; 
    console.log(this.sharingData)
  }
  getData()
  {
    console.log('get data function called');
    return this.sharingData;
  }
} 

在组件级别设置providers数组时,这意味着在这种情况下,您具有两个单独的实例。

您需要在NgModule providers数组中声明服务,然后两个组件(以及该模块中的任何其他组件(将具有服务的相同实例。

因此,请删除组件中的providers数组,而是将服务添加到NgModule中的提供商数组。

@Component({
  selector: 'app-ctwo',
  templateUrl: './ctwo.component.html',
  styleUrls: ['./ctwo.component.css'],
  // providers: [SharedService] // remove these!
})

,而不是....

@NgModule({
  imports: [ ... ],
  declarations: [ .. ],
  bootstrap: [ ... ],
  providers: [ SharedService ] // here!
})

最新更新