【问题标题】:Passing data from child to parent component in angular via <router-outlet>通过 <router-outlet> 以角度将数据从子组件传递到父组件
【发布时间】:2022-10-13 17:19:41
【问题描述】:

在 app.component.html 我有

<div>
    <app-login (un)="doSth($event)"></app-login>
</div>
<router-outlet (un)="doSth($event)"></router-outlet>

在 app.component.ts 我有

export class AppComponent {
  title = 'order';
  uname = 'guest';

  doSth (name:any) {
    console.log("name", name);
    this.uname = name;
  }
}

我遇到的问题是,当我使用标签&lt;app-login&gt; 时,我将数据获取到app.component.ts,但当我使用标签&lt;router-outlet&gt; 时却没有。为什么会这样,我该如何解决?

【问题讨论】:

  • 只需使用服务。

标签: angular components parameter-passing eventemitter


【解决方案1】:

您可以在角度使用@Output 在文件login.component.ts

import { Output, EventEmitter } from '@angular/core';
@Output() un= new EventEmitter<any>();

// handle emit name form html
getName(event:any) {
 this.un.emit(event.tagret)
}

【讨论】:

    【解决方案2】:

    我不认为路由器可以做到这一点。

    您需要在应用程序中发送消息的是像 NgRX 这样的状态管理存储。 但是为了简单起见,您还可以有一个单例主题,每个感兴趣的人都可以订阅。

    例子: 消息服务.ts

    @Injectable({ providedIn: 'root' })
    export class MessagingService {
      public messages$ = new Subject();
    }
    

    app.component.ts

    export class AppComponent {
      title = 'order';
      uname = 'guest';
    
      constructor(readonly messaging: MessagingService) {
        messaging.messages$.subscribe(event => {
          this.doSth(event);
        }
      }
    
      doSth (name:any) {
        console.log("name", name);
        this.uname = name;
      }
    }
    

    login.component.ts (以及您想要在router-outlet 中的所有组件:

    export class LoginComponent {
      constructor(private readonly messaging: MessagingService) {}
    
      iWantAppComponentToDoSth() {
         messaging.messages$.next({ name: 'foo' });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 2017-05-18
      • 2020-08-24
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2020-03-04
      • 2017-09-01
      • 1970-01-01
      相关资源
      最近更新 更多