在带有服务的组件之间传递对象

时间:2016-12-30 15:45:55

标签: angular

我在几页中读到,在进行路由时,在组件之间传递对象的最佳方法是使用服务。

我依赖于最后一个例子(http://plnkr.co/edit/NpLKAgY3FkzhOK9eBeIb?p=preview),我制作了以下代码给我带来了问题:

服务:

@Injectable()
export class tableService {

    public category: Category;
}

组件1:

export class tableComponent {
    categorys: Category[] = []; 
    category: Category;

passItemCat(event: any) {
    this.category = {
        Code: "09",
        Attachments: [],
        Description: "eee",
        Response: {
            Destination: "",
            HtmlText: "",
            Text: "",
            Type: "",
        },
        Taxonomy: "ddd",
     }
    event.preventDefault(); 
}


constructor(public _tableService: tableService) { }

ngOnInit(): void {
    //get API for categorys
}

ngOnDestroy() {
    this._tableService.category = this.category;
}
}

模板组件1

<tr *ngFor="let item of categorys">
            <td>
                <nav>
                    <button routerLink="/ModifyCategory" routerLinkActive="active" class="btn btn-warning" (click)="passItemCat($event)">Modify</button>
                </nav>
            </td>

Componente 2

export class modifyCategoryComponent{
    category: Category;

    constructor(public _tableService: tableService) { }

    ngOnInit() {
        this.category = this._tableService.category;
    }
}

问题发生在组件2的OnInit上,它在this._tableService.category中找不到元素。

PS。在这个步骤中(我按小步骤学习)在点击时使用静态类别,随后我想阅读组件模板的项目1.如果你想建议一些改进都是耳朵。

1 个答案:

答案 0 :(得分:2)

这可能是因为modifyCategoryComponent_tableservice.category设置tableComponent之前读取_tableService.category

如果您改为使用Observable,则在设置或更新值时会通知接收组件。

@Injectable()
export class tableService {
  private category:BehaviorSubject<Category> = new BehaviorSubject<Category>(null);
  get $category() {
    return this.category.asObservable();
  }
  setCategory(value:Category) {
    this.category.next(value);
  }
}

设置新类别

ngOnDestroy() {
  this._tableService.setCategory(this.category);
}

订阅类别更改

ngOnInit() {
    this._tableService.$category.subscribe(value => this._tableService.category = value);
}

另见https://angular.io/docs/ts/latest/cookbook/component-communication.html