Angular 2中的共享服务和异步数据

时间:2017-08-18 20:04:11

标签: javascript angular typescript asynchronous

我遇到通过共享服务获取数据的问题

我有Shared Service

@Injectable()
export class SharedService {
  public title;
  constructor() {
    this.title = "";
  }

  public setData(val: string): void {
    this.title = val;
  }

  public getUrlHistoryObj(): string {
    return this.title;
  }
}

我从DataService获取数据的组件FillComponent(它可以运行,它获取数据并实际设置数据,使用console.log对其进行测试)

export class FillComponent implements OnInit {
  @Input() title: any;
  constructor(public info: InfoComponent, public shared: SharedService) {

  }

  ngOnInit() {
    this.shared.setData(this.title); }
}

我从PartComponent

获取数据
export class Part2Component implements OnInit {
  @ViewChild(FillInBlankComponent) private fill: FillComponent;
  @ViewChild(InfoComponent) private info: InfoComponent;
  public title: string;

  constructor(public dataService: DataService, public shared: SharedService) {
    this.dataService.get().subscribe(data => {
      const d = this.dataService.convert(data, 2);

      this.title = d[0];

    });
  }

直到现在一切正常。

但问题在于,在InfoComponent中,当我尝试获取数据时,它会给我空结果。

@Injectable()
  export class InfoComponent implements OnChanges, OnInit, OnDestroy {

  public title: string;

  constructor(public shared: SharedService) {

   this.title = this.shared.getUrlHistoryObj();

  }

  ngOnInit() {
    console.log('i am title from info and i am boos')
    console.log(this.title)
}
}

我猜问题出在异步加载中。我怎么能解决它?

1 个答案:

答案 0 :(得分:0)

在信息组件上,将此行移到构造函数之外的ngOnInit:

  

this.title = this.shared.getUrlHistoryObj();