0

每个人!

我需要你的帮助。我的 Angular 10 应用程序中有一个组件,我们将其命名为 A。

在这个组件中,我还有<router-outlet>routes.ts 文件中描述的路由。

我需要的是通过单击某个 B 组件中的按钮来更改 A 组件内的变量(字段),即 route inside <router-outlet>。我该怎么做?

例如,我们可以谈论这样的变体。

A.component.html

<B [changeFieldOfA]="func"></B>

组件.ts

export class A {
    foo: string = "";
    func() {
        this.foo = "bar";
    }
}

这一切都很酷,因为我可以传递函数,将我的 A 组件字段更改为我的组件。

但是如果我有这个变种呢?:

A.component.html

<router-outlet></router-outlet>

路线.ts

{path: "b", component: B}

我想调用这个 func(),它属于 B 内部的 A(并更改其字段),但我不能再通过 Input() 来做,因为在路由器中我做不到。

4

1 回答 1

1

Demo可以使用 service 在组件之间进行通信

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}    
}

投入使用

this.shareService.setParam('Sending param');

从服务中获得

 this.shareService.sharedData.subscribe(data=> { this.your_variable=data })

构造函数喜欢

constructor(private shareService: ShareService  ){}
于 2020-07-22T17:36:24.083 回答