繁体   English   中英

Angular2:通过路由器在同级组件之间传递数据吗?

[英]Angular2: Passing data between sibling components through routers?

我是Angular2的新手。 我一直在通过官方文档,Mosh稍微过时的udemy课程以及一本名为ng-book2的书来学习我所学的东西。

我所拥有的是总是在页面顶部的表格。 它的下面是数据库列表。 单击列表中的一个项目,将整个列表替换为该项目的详细信息。 单击后退按钮可将您带回到清单。 表格仍然在最上面。 这是一个基本的CRUD应用程序。 提交表单会将新项目保存到数据库。

问题是当我提交表单时,列表不会自动获取新项目:相反,我必须刷新页面。 其他操作(upvote,downvote,delete)工作正常。

app.component.html:

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

路由器出口显示物品清单或物品详细信息。

程序体系结构 :我有一个用于表单的单独组件(ArticleFormComponent),一个用于列表的单独组件(ArticlesComponent)和一个用于详细信息的单独组件(ArticleDetailComponent)。 路由在ArticlesComponent和ArticleDetailComponent之间。

我基本上是希望ArticleFormComponent通知其同级ArticlesComponent已提交了新的Article,并且我希望ArticlesComponent接收该Article并将其push()在Articles []数组中。

我用google搜索了一下,试图实现一个发射器服务来广播事件,但是问题是我使用的是路由器插座,却不知道该如何设置输入属性。 有人可以指引我正确的方向吗? 谢谢。

例如,您可以仅使用RxJS的ReplySubject类来实现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();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM