从路由树中的另一个组件获取数据

Get data from another component in the route tree

例如,您有组件 A、B 和 C 以及此路线方向:

A -> B -> C

我可以从前一个组件中检索数据(到达 C 并从 B 获取数据) 使用这些行:

组件 C:

private _activatedRoute: ActivatedRoute,

ngOnInit(): void {
        let B_ID = this._activatedRoute.snapshot.queryParams['B_ID'];
}

但我想从组件 A 中检索数据:

组件 C:

private _activatedRoute: ActivatedRoute,

ngOnInit(): void {
       // let A_ID = this._activatedRoute.parent.snapshot.queryParams['A_ID'];
//Didnt retrieve the A ID
}

您可以通过订阅router.events功能来获取路由器数据。
你可以这样做

this.router.events.subscribe(val => {

if (val instanceof RoutesRecognized) {
   console.log(val.state.root.queryParams);
    console.log( this.router.config)
}});

探索 val 对象,您可以获得特定路线的值

我所做的是创建一个服务来在组件之间共享信息,例如:

import { Injectable } from '@angular/core';
import {HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UtilsService {
  information:any;
.
.
.

然后你可以在创建服务的信息变量中保存离开A之前的信息。 现在您可以从组件 C 的服务中读取信息变量中的内容了。

记得导入服务并将其添加到组件的构造函数中

import { UtilsService } from '../../providers/utils.service';

_

constructor(
    private utilsSvc: UtilsService,
  ) {

您可以通过this.utilsSvc.information访问它。

如果你想在组件之间进行通信,你可以使用主题轻松地做到这一点。

举个你提到的例子,你有 3 个组件 A、B、C 那么如果你想从 A 组件中获取数据到 C 组件,你必须先创建一个服务

前-

 export class DatapassAtoCService{

  private messageCommand = new Subject<string>();
  Data$ = this.messageCommand.asObservable();

  invokeMessage(msg: string) {
    this.messageCommand.next(msg);
  }
}

在这个例子中,我传递值 msg,它是组件 A 中的类型字符串,以服务此服务使用一个可观察的主题,它发出在服务中订阅此方法的值,如下所示。

import { Component, OnInit } from '@angular/core';
import { DatapassAtoCService} from '../services/message.service';

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

  constructor(private DataService: DatapassAtoCService) { }

  ngOnInit() {
  }
  string msg =This is pass to service;
  yourActionMethod() {
    this.DataService.invokeMessage(msg );
  }
} 

然后我们可以在 C 组件中订阅该服务,然后发出 msg 值

import { Component, OnInit, OnDestroy } from '@angular/core';
import { DatapassAtoCService} from '../services/message.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.css']
})
export class CComponent implements OnInit, OnDestroy {

  messageSubscription: Subscription;
  message: string;

  constructor(private Dataservice: DatapassAtoCService) { }

  ngOnInit() {
    this.subscribeToMessageEvents();
  }

  ngOnDestroy(): void {
    this.Dataservice.unsubscribe();
  }

  subscribeToMessageEvents() {
    this.messageSubscription = this.Dataservice.Data$.subscribe(
      (msg: string) => {
        this.message = msg;
      }
    );
  }

}

因此如上面代码中所述,我们可以使用 Ccomponent 中的 messageSubscription 获取 Acomponent msg 值