angular - 通过服务将父路由参数传递给子路由

标签 angular angular-routing

我正在尝试使用 Angular 团队当前推荐的方法将路由参数从父组件传递到子组件:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

父级能够成功订阅正确发出的服务。但是,当页面加载时,子级不会收到任何内容。

服务

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

父级

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);
      });
  }
}

最佳答案

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

关于angular - 通过服务将父路由参数传递给子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280325/

相关文章:

javascript - 使用 Angular-route 构建带有 > 1 个斜杠的模板路由时出现问题

Angular:路由多个 id(父级和子级)

angular - 错误类型错误 : Cannot read property 'invalid' of null Angular 8

javascript - 如何在 Angular 组件的输入元素上正确设置 ID?

css - Domsanitizer bypasssecuritytruststyle 在 ie 11 中不起作用

javascript - 避免使用 ng-route 路由无哈希 url

javascript - Angular 2 RC5 及更高版本 - 当没有路由匹配时如何显示错误页面?

angular - 使用 HTTPErrorResponse 处理 HTTP 错误 - 组件还是服务?

AngularJS:部分 View 未呈现

javascript - 如何在angularjs中执行路由