Angular2:通过路由器在兄弟组件之间传递数据?

Angular2: Passing data between sibling components through routers?

我是 Angular2 的新手。我主要通过官方文档、Mosh 的一门稍微过时的 udemy 课程和一本名为 ng-book2 的书来学习我所拥有的东西。

我有什么 是一种始终存在于页面(顶部)的表单。在它下面是数据库中的列表。单击列表中的项目会将整个列表替换为该项目的详细信息。单击后退按钮可返回列表。表格保留在顶部。这是一个基本的 CRUD 应用程序。提交表单会将新项目保存到数据库。

问题 是当我提交表单时,列表不会自动获取新项目:相反我必须刷新页面。其他操作(赞成票、反对票、删除)工作正常。

app.component.html:

<app-article-form [listid]="listid" [formid]="formid"></app-article-form>
<router-outlet></router-outlet>

路由器出口显示项目列表或项目详细信息。

程序架构: 我有一个单独的表单组件 (ArticleFormComponent)、一个单独的列表组件 (ArticlesComponent) 和一个单独的细节组件 (ArticleDetailComponent)。路由位于 ArticlesComponent 和 ArticleDetailComponent 之间。

我基本上希望 ArticleFormComponent 通知它的兄弟 ArticlesComponent 已提交新文章,并且我希望 ArticlesComponent 接收该文章并将其 push() 到 Articles[] 数组中。

我在谷歌上搜索了一下并尝试实现发射器服务来广播事件,但问题是我使用的是路由器插座,但不知道如何在其中设置输入属性。有人可以指导我正确的方向吗?谢谢

例如,您可以仅使用 RxJS 的 ReplySubject class 来实现 PubSub 模式。方法如下:

import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';

@Injectable()
export class ArticlesPubSubService extends ReplaySubject<IArticle> {

  constructor() {
    super();
  }

}

然后在两个组件中使用此 ArticlesPubSubService

1) 在 articles-form.component.ts 中,您将发出新创建的文章:

import { Component, OnInit } from '@angular/core';
import { ArticlesPubSubService } from '../articles-pub-sub.service';

@Component({
  selector: 'so-articles-form',
  templateUrl: './articles-form.component.html',
  styleUrls: ['./articles-form.component.css']
})
export class ArticlesFormComponent implements OnInit {

  constructor(private aps: ArticlesPubSubService) { }

  ngOnInit() {
  }

  submit(article) {
    // ... 
    this.aps.next(article);
  }

}

2) 在 articles.component.ts 中,您将获得这篇新文章并将其推送到您的本地文章列表:

import { Component, OnInit } from '@angular/core';
import { ArticlesPubSubService } from '../articles-pub-sub.service';

@Component({
  selector: 'so-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {

  articles: IArticles[];

  constructor(private aps: ArticlesPubSubService) { }

  ngOnInit() {
    this.aps.subscribe( article => this.articles.push(article) );
  }
  ngOnDestroy() {
    this.aps.unsubscribe();
  }
}