在具有角度2的共享服务之间未定义数据

时间:2016-06-30 20:15:39

标签: angular angular2-services

路线

export const SchoolyearsRoutes: RouterConfig = [
  { path: '', terminal: true, redirectTo: '/schoolyears' },
  {
    path: 'schoolyears', component: SchoolyearsRootComponent, children: [
      { path: '', component: SchoolyearsListComponent },
      { path: 'edit/:id', component: SchoolyearsEditComponent },
      { path: 'create', component: SchoolyearsCreateComponent }
    ]
  }];

服务

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Schoolyear } from './schoolyear';


@Injectable()
export class SchoolyearsEditService {

    public schoolyear: Schoolyear;

    constructor() { }
}

父组件:

import { Component }            from '@angular/core';
import { ROUTER_DIRECTIVES }    from '@angular/router';
import { SchoolyearsEditService } from '../schoolyears-edit.service';

@Component({  template:`<router-outlet></router-outlet>`,  providers: [SchoolyearsEditService]})
export class SchoolyearsRootComponent { }

子组件:

import { Component, OnInit } from '@angular/core';
import { RouterConfig, Router, ActivatedRoute} from '@angular/router';
import { SchoolyearsEditService } from '../schoolyears-edit.service';
import { Schoolyear } from '../schoolyear';

@Component({
  moduleId: module.id,
  selector: 'app-schoolyears-edit',
  templateUrl: 'schoolyears-edit.component.html',
  styleUrls: ['schoolyears-edit.component.css'],
})
export class SchoolyearsEditComponent implements OnInit {
  schoolyear: Schoolyear;
  constructor(private route: ActivatedRoute, private router: Router, private schoolyearsService: SchoolyearsEditService) { }

  ngOnInit() {
    this.schoolyear = this.schoolyearsService.schoolyear;
  };
}

HTML

schoolyear Id:
<input [value]="schoolyear.id">

schoolyear name:    
<input [value]="schoolyear.name">

schoolyear start date:
<input [value]="schoolyear.startDate">

schoolyear end date:    
<input [value]="schoolyear.endDate">

html中的schoolyear总是未定义的。

为什么数据未正确共享?

我在父组件中提供服务并在子组件中共享它。它应该工作,但不是!

2 个答案:

答案 0 :(得分:1)

它可能是正确共享的,但是当DOM已经渲染时,它的学习价值太晚了。您可以使用elvis运算符或所谓的安全导航运算符来缓解此问题。

schoolyear Id:
<input [value]="schoolyear?.id">

schoolyear name:    
<input [value]="schoolyear?.name">

schoolyear start date:
<input [value]="schoolyear?.startDate">

schoolyear end date:    
<input [value]="schoolyear?.endDate">

这样,只要schoolyear变量被填充,它就会将值输入到输入中。

答案 1 :(得分:1)

您正在复制原始值

  ngOnInit() {
    this.schoolyear = this.schoolyearsService.schoolyear;
  }

这不会在服务和组件之间建立连接。这是一次性行动。

如果服务在复制时尚未设置(上面的代码),那么它就不会发生。

使用Observable,在这种情况下,向新订阅者发出最后一次发出的事件的BehaviorSubject可能是更好的选择。

有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html