通过服务将父级路线参数传递给孩子 [英] Passing parent route params to child via service

查看:62
本文介绍了通过服务将父级路线参数传递给孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Angular小组当前建议的方法将路由参数从父组件传递到子组件:解决方案

我认为代码是正确的,但是事件丢失了.在您下次拨打电话时,没有人在听主题.一种方法是使用ReplaySubject,另一种方法是在ngAfterViewInit回调中调用下一个.

I am trying to pass route parameters from a parent component to child component using the method that the Angular team currently recommends: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

The parent is able to successfully subscribe to the service which does emit correctly. However, the child does not receive anything when the page is loaded.

Service

@Injectable()
export class AbcService {
  public paramSource: Subject<any> = new Subject<any>();
  public getParams(params) {
    this.paramSource.next(params);
  }
}

Parent

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AbcService } from './abc.service';

@Component({
  providers: [AbcService],
  ...,
})

export class AbcComponent {
  constructor(
    private route: ActivatedRoute,
    private abcService: AbcService,
  ) {
    route.params.subscribe(
      (params) => abcService.getParams(params);
    );
  }
}

Child

export class AbcChildComponent {
  constructor(private abcService: AbcService) {
      abcService.paramSource.subscribe((params) => {
          console.log(params);
      });
  }
}

解决方案

I think code is correct, but event was lost. At the time you call next, nobody is listening to subject. One way is to use ReplaySubject another is to call next in ngAfterViewInit callback.

这篇关于通过服务将父级路线参数传递给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆