0

例如,您有组件 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
}
4

3 回答 3

0

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

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

于 2019-03-22T11:03:27.223 回答
0

如果您想在组件之间进行通信,您可以使用主题轻松完成。

对于您提到的示例,您有 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 值

于 2019-03-22T11:14:04.277 回答
0

您可以通过订阅 router.events 函数来获取路由器数据。
你可以做这样的事情

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

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

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

于 2019-03-22T10:46:52.580 回答