Angular2在组件不同的模块之间共享数据

时间:2018-06-28 19:13:39

标签: angular2-services

我有需要在模块之间共享数据的要求, 我的文件夹结构是这样的

app(folder)
  app.module.ts
  app.component.ts
service(folder)
  abc.service.ts
student(folder)
  student.module.ts
  student.component.ts

在这里,我有abc.service.ts文件,其中我正在设置一些数据,例如

    private scoreList= new Subject<any>();
   setList(val){
      this.scoreList.next(val);
    }

    getList(){
      return this.scoreList.asObservable();
    }

在app.module.ts中

     declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    studentModule,
    HttpModule,
  ],
  providers: [
    abcService
  ],

在app.component.ts中,我正在调用api并将其设置为setList,并尝试在Student.component.ts中获取值,但是当我将调试器放入getList中时,它没有显示值,而显示长度为0的数组我在setList函数内部,它正在显示值。

谢谢

1 个答案:

答案 0 :(得分:0)

iam在这里为您创建了工作示例https://stackblitz.com/edit/angular-gebnnq

app.component.ts

// iam declared sample data you can replace whatever data array.
records = [
      { CategoryID: 1, CategoryName: "Beverages", Description: "Coffees, teas" },
      { CategoryID: 2, CategoryName: "Condiments", Description: "Sweet and savory sauces" },
      { CategoryID: 3, CategoryName: "Confections", Description: "Desserts and candies" }    
    ];

  constructor(private _abc:AbcService){

    this._abc.setList(this.records);
    console.log("Service Value has been set",this._abc.scoreList);
  }

app.html

<app-student></app-student>

app.module.ts

import { AbcService } from './abc.service';
import { StudentComponent } from './student/student.component'

declarations: [ AppComponent, HelloComponent,StudentComponent ]

app.service.ts

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

@Injectable()
export class AbcService {
    private scoreList: any[] = [];

    constructor() { }

    setList(val) {
        this.scoreList = val;
    }

    getList() {
        return this.scoreList;
    }
}

Student.component.ts

import { Component, OnInit } from '@angular/core';
import { AbcService } from '../abc.service';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html'
})
export class StudentComponent implements OnInit {
  result:any[]=[];
  constructor(private _abc:AbcService) { }

  ngOnInit() {
    this.result=this._abc.getList();
    //also use like, this.result=this._abc.scoreList
    console.log("Result Value get from Student Component",this.result);
  }

}

Student.html

Here Displayed Results
<ng-container *ngIf="result">
  <li *ngFor="let item of result">
  {{item.CategoryName}}
  </li>
</ng-container>

iam在此根据示例数据替换了您的数据。

屏幕截图

enter image description here

我希望这会有所帮助。

谢谢

Muthukumar