【问题标题】:Angular: Passing data or events from child to parent with router-outletAngular:使用路由器出口将数据或事件从子级传递给父级
【发布时间】:2018-07-31 18:41:52
【问题描述】:

我有带有路由登录、主页等的父 AppComponent。当用户使用凭据登录时,我将用户凭据保存在 Sessionstorage 中。当登录成功时,我想在 AppComponent.html 的 header 中显示部分数据,所以我必须从 seesiontorage 中获取项目。如何触发事件以从 LoginComponent 通知 AppComponent?我正在使用路由器插座,所以我不能使用 EventEmitter。我可以使用 BehaviourSubject,但 AppComponent 中没有有效的方法可以调用。 请提出建议。

【问题讨论】:

  • 如果登录组件中执行了某些操作,您是否只想签入 Appcomponent ?您可以使用通信服务将您的更改发送到其他组件
  • @warrior 我希望 AppComponent 在 LoginComponent 中登录成功时从 sessionStorage 中获取数据
  • 你可以通过事件发射器来做到这一点
  • 是的,登录后您可以从 logincomponent 向 appComponent 发出更改,并且在您的 appcomponent 中您可以从存储中获取数据
  • @warrior 由于它是路由器出口,我如何发出事件? AppComponent中没有直接注入登录选择器或模板

标签: angular


【解决方案1】:

为此使用通信服务:

CommunicationService.ts

@Injectable()
export class CommunicationService {
    constructor() { }

    private emitChangeSource = new Subject<any>();

    changeEmitted$ = this.emitChangeSource.asObservable();

    emitChange() {
        this.emitChangeSource.next();
    }
}

login.ts:

constructor(
    private communicationService: CommunicationService
    ) {
   }

   login(){
    this.communicationService.emitChange()
   }

AppComponent.ts:

constructor(
    private communicationService: CommunicationService,
    ) { 
    communicationService.changeEmitted$.subscribe(data => {
      // here fetch data from the session storage 
    })
  }

希望这会有所帮助。

【讨论】:

  • 你能解释一下你的解决方案吗@Aakriti.G
  • 这就是我要找的东西谢谢@Aakriti.G
【解决方案2】:

我只是稍微扩展一下“Hrishikesh Kale”的答案,在您看来,您将用户凭据存储在本地存储中。

只需在服务中获取存储的数据

credentials(){
    const usercredential = localStorage.getItem('usercredential')
    if(usercredential === "undefined"){
      return false
    }
    else {
      return true
    }
  }

在你的 html 中

<a *ngIf="service.loggedIn() && service.credentials()">Admin</a>

【讨论】:

  • 你可以根据需要修改逻辑 return true |假
猜你喜欢
  • 2020-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多