【问题标题】:How do two different components communicate with one another?两个不同的组件如何相互通信?
【发布时间】:2016-11-04 15:49:48
【问题描述】:

我正在使用 Provider 注入器将命令从 Signin 组件发送到 Profile 组件以注销。尽管控制台日志显示 Signout 功能已按预期工作,但 (HTML) *ngIf 指令并未相应更改。

我做错了什么?

**Signin component**

import {Component, OnInit,  Injectable  } from '@angular/core';

import {ProfileUserComponent} from '../profile.user.component/profile.user.component'


@Component({
  selector: 'signin-button',
  template: `<button (click)="onSignOut()"  *ngIf="loggedIn === true "  >Sign Out</button> 
<button  (click)="onSignIn()"  *ngIf="loggedIn !== true "  >Sign In</button> 
`,
  providers: [ProfileUserComponent]


})




@Injectable()
export class SigninComponent { 

loggedIn: boolean;

constructor(public http: Http, private profileUserComponent: ProfileUserComponent ){}

      ngOnInit(): any{}

onSignOut(): void{

// send command to the profile component
this.profileUserComponent.signout(false);     

}

}





 **ProfileUserComponent**
import {Component, OnInit, Injectable} from '@angular/core';



    @Component({
            selector:'profile-user',
            template: `<img class="ui mini image" src="image1.jpg" *ngIf="loggedIn === true">

    <img class="ui mini image" src="image2.jpg" *ngIf="loggedIn === false">

    `,

    })

      signout(status){
        this.loggedIn = status;
        console.log ("logged out", this.loggedIn);  // Console log tells me that "Logged Out False"
}     


}

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

    您的整个代码需要重新编写。您试图将一个组件注入另一个组件,这是错误的。您将服务注入到组件中。

    如果 ProfileUserComponent 和 SigninComponent 都必须是带有 UI 的组件,那么您可以创建一个知道登录状态并注入到两个组件中的公共服务。一个组件可以在服务的属性上设置登录状态(例如 isSignedIn: EventEmitter),它会发送一个关于登录状态的事件,另一个组件会监听这个事件。

    附注:@Injectable 注解不与组件一起使用。

    【讨论】:

    • 嗨 Yakov,如果我理解正确的话,构建 *ProfileUserComponent 的正确方法是让该组件监听更改?这是不同的,因为现在在 Angular2 中我们使用 Rxjs 库?
    • 如果同时显示两个同级组件,则引入一个服务并让第一个组件修改该服务,每次修改都会触发一个事件。如果将此服务注入第二个组件,它可以订阅这些事件:myCommonService.varOfTypeEventEmitter.subscribe()。另一种情况是使用路由器。如果第二个组件显示在路由器出口中,它可以通过订阅 ActivatedRoute 的 params 属性来订阅第一个组件的更新(它必须被注入到第二个组件中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多