通过角度2中的多个组件访问服务的属性?

时间:2017-04-15 05:31:00

标签: angular typescript angular2-services

我有在组件1中计算的属性,我使用服务来访问和存储该属性,并从另一个组件访问该属性值,但该值不会反映在另一个组件中。我做错了什么

组件1

 import { Component, AfterViewInit } from '@angular/core';
import { CrosspropertiesService } from "../services/Crossproperties.service";
@Component({
  selector: 'app-timer',
  templateUrl: './timer.component.html',
  styleUrls: ['./timer.component.css'],
  providers:[CrosspropertiesService]
})
export class TimerComponent implements AfterViewInit {
  constructor(private crossproperties: CrosspropertiesService) { }
  public projectheader: number = 959 ;//lets assume
  ngAfterViewInit() {
    this.projectheader = this.crossproperties.projectHeaderWidth;
    console.log(this.crossproperties.projectHeaderWidth);// console has value 959
    }

  }

}

组件2

    import { Component, AfterViewInit, Input } from '@angular/core';
    import { CrosspropertiesService } from "../../services/Crossproperties.service";
    @Component({
      selector: 'app-projects',
      templateUrl: './projects.component.html',
      styleUrls: ['./projects.component.css'],
      providers:[CrosspropertiesService]
    })
    export class ProjectsComponent implements AfterViewInit {

      constructor(private crossproperties: CrosspropertiesService ) { }

      public headerWidth :number;
      ngAfterViewInit() {
        this.headerWidth= this.crossproperties.projectHeaderWidth;
        console.log(this.headerWidth); //console has value undefined 
      }

和服务文件

import { Injectable } from '@angular/core';
@Injectable()
export class CrosspropertiesService {
  public projectHeaderWidth:number;
  constructor() { }
}

1 个答案:

答案 0 :(得分:1)

如果在组件上向providers数组添加服务,则每个组件都会获得自己的实例服务。

从组件中删除providers属性,并将其添加到父组件或NgModule

@NgModule({
  ...
  providers: [CrosspropertiesService]
})
export class AppModule {}