将数据绑定到角度2路由组件

时间:2016-01-19 19:27:51

标签: angular angular2-routing

我目前使用以下模板

<project-form [nextId]="projects.length" (newProject)="addProject($event)"></project-form>
<project-list [projects]="projects"></project-list>

在ProjectAppComponent中。

class ProjectAppComponent {
    projects: Project[] = [
        { id: 0, title: "Build the issue tracker" },
        { id: 1, title: "Basecamp" },
    ]

    addProject(project: Project) {
        this.projects.push(project);
    } 
}

ProjectAppComponent具有项目数组和将新项目推入其中的方法。我想为项目表单和项目列表创建子路由,这样我就可以/projects/new/projects/show来显示表单或列表。我创建了这样的路线配置 -

@Component({
    template: `
        <div>
            <router-outlet></router-outlet>
        </div>
    `,
    directives: [ RouterOutlet ]
})
@RouteConfig([
    { path: '/list', name: 'ProjectList', component: ProjectListComponent, useAsDefault: true },
    { path: '/new', name: 'ProjectForm', component: ProjectFormComponent },
])
class ProjectAppComponent {
    projects: Project[] = [
        { id: 0, title: "Build the issue tracker" },
        { id: 1, title: "Basecamp" },
    ]

    addProject(project: Project) {
        this.projects.push(project);
    } 
}

用于ProjectAppComponent类本身。现在的问题是我不知道如何将项目数组(模板中的[projects]="projects")传递给ProjectListComponent,因为不再使用<project-list>选择器(必须使用{{ 1}})。 ProjectListComponent依赖于<router-outlet>来呈现所有项目。我该如何解决这个问题?这是项目列表组件 -

@Input() project: Project

1 个答案:

答案 0 :(得分:6)

你能不能只使用一项服务?

import {Injectable} from 'angular2/core';
import {Project} from '...';


@Injectable()
export class ProjectService {
  public projects: Project[] = [
    { id: 0, title: "Build the issue tracker" },
    { id: 1, title: "Basecamp" },
  ];

  addProject(...args): number {
    return this.projects.push(new Project(...args));
  }
}