我已经有一段时间了,很多文章,文档,很多试验和错误,但我觉得我错过了一些核心 .
本质上,我正在尝试创建一个可扩展的导航组件,其他组件可以在添加到页面时添加项目 . 我试图通过几种方式实现这一点,包括一个服务,这个例子我通过将一个组件注入另一个组件来尝试它 .
我有一个包含项目列表的组件,我有一个ngFor循环项目并显示文本 . 我在页面上有一个按钮,当您单击时向项目添加项目 . 我还将组件注入另一个组件,我已经在NgOnInit()上添加了一个项目(尝试了其他生命周期事件和构造函数) .
奇怪的是,当按钮将项目添加到数组时,列表会更新,但是当其他组件添加项目列表时,即使项目计数增加,我也无法更新UI,我可以在UI中看到组件具有已加载并呈现默认项目 .
import {Component} from 'angular2/core';
import {Router, RouteParams} from 'angular2/router';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Injectable} from 'angular2/core';
@Component({
selector: 'caseBasedSearchSidebar',
template: `<ul id="sidebar-wrapper" class="clearfix nav navbar-default sidebar-nav">
<li *ngFor="#nav of navigationItems">
<span>{{nav.name}}</span>
</li>
<ul> <button (click)=addNavigationItem()>Add</button> `,
directives: [ROUTER_DIRECTIVES] })
@Injectable() export class SidebarComponent {
public navigationItems: Array<ISideNavigationItem>;
constructor() {
this.navigationItems = [{ name: 'test' }];
}
public addNavigationItem(item: ISideNavigationItem) {
this.navigationItems.push({ name: 'test' });
}
}
export interface ISideNavigationItem {
name: string; }
import {Component, OnInit} from 'angular2/core';
import {SidebarComponent} from '../sideBar.component';
@Component({
templateUrl: '/CaseBasedSearch/PatientInformation',
providers: [SidebarComponent]
})
export class PatientInformationComponent implements OnInit {
private sideBarComponent: SidebarComponent;
constructor(sideBarComponent: SidebarComponent) {
this.sideBarComponent = sideBarComponent;
}
ngOnInit() {
this.sideBarComponent.addNavigationItem({ name: 'testing' });
}
}
任何指导表示赞赏 .
3 回答
您正在
SidebarComponent
中分配navigationItems
模型 . 对此模型的更改不会传播到其他组件 .考虑将
navigationItems
设置为@Input属性:并将模型从父组件(PatientInformationComponent)传递到子组件(SidebarComponent):
此外,作为惯例,SidebarComponent中的选择器应该是蛇形的:
正如其他人所说:
SidebarComponent不是服务 . 您不需要将其注入构造函数中,也不需要将其添加到providers属性中 .
应删除组件的@Injectable属性 .
最终我的问题是注入服务/组件的范围 . 我在每个组件上使用提供者项目,并且使用服务,这导致每个服务都拥有它自己的实例 . 当组件更新服务时,它没有更新先前测试使我相信它的相同阵列 . 我将注入移动到boot.ts它们都开始获得相同的实例 . 回答here .
最终的代码;
也许您应该删除
SidebarComponent
组件的@Injectable
装饰器,并且只保留@Component
.希望它对你有帮助,蒂埃里