错误TypeError:“ this.ngChatInstance未定义”

时间:2018-12-06 11:23:40

标签: angular typescript

我收到错误TypeError:当我单击“从导航栏聊天”时,“ this.ngChatInstance未定义”没有错误,但是当单击“从页面聊天”时,我得到了错误。

我正在使用ng-chat

navbar.component.html

<p> navbar works!</p>
<a (click)="clickchat()">Chat from navbar</a> &nbsp;&nbsp;&nbsp;
<a (click)="clickchatclose()">close from navbar</a>
<ng-chat #ngChatInstance [adapter]="adapter" [userId]="999" [historyEnabled]="true" [historyPageSize]="4" [hideFriendsList]="false" (onMessagesSeen)="messageSeen($event)"></ng-chat>

navbar.componenet.ts

import { ChatAdapter,IChatController,UserStatus } from 'ng-chat'; 
import { DemoAdapter } from './demo-adapter';

export class NavbarComponent implements OnInit {
@ViewChild('ngChatInstance')
protected ngChatInstance: IChatController;
constructor() { }

ngOnInit() {
}

public adapter: ChatAdapter = new DemoAdapter();

public messageSeen(event: any)
{
  console.log(event);
}

public clickchat(){
  let user:any = {
  id: 2,
  displayName: "Cersei Lannister",
avatar: null,
status: UserStatus.Online
};
  console.log(user);
  console.log(this.ngChatInstance);
this.ngChatInstance.triggerOpenChatWindow(user);
}

public clickchatclose(){
this.ngChatInstance.triggerCloseChatWindow(2);
 }
 }

page.componenet.ts

import { NavbarComponent } from '../navbar/navbar.component';

export class PageComponent implements OnInit {
@ViewChild('ngChatInstance')
protected ngChatInstance: IChatController;

constructor(
  public navbar: NavbarComponent
) { }

ngOnInit() {
}
clickchatformpage(){
this.navbar.clickchat();

}

clickchatcloseformpage(){

}
}

page.componenet.html

<p>
 page works!
</p>
<a (click)="clickchatformpage()">Chat from page</a> &nbsp;&nbsp;&nbsp;
<a (click)="clickchatcloseformpage()">close from page</a>

请参见示例link

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要在navbar内获得对page.component.ts的引用 实现此目的的一种方法是在应用程序组件内部获取导航栏的引用

export class AppComponent  {
  @ViewChild(NavbarComponent) public navbar: NavbarComponent;
}

然后,将应用程序组件注入页面组件的构造函数中,并使用对应用程序组件导航栏的引用:

export class PageComponent implements OnInit {

  constructor(
    @Inject(AppComponent) private appComponent: AppComponent
  ) { }

  clickchatformpage(){
    this.appComponent.navbar.clickchat();
  }

这是您的示例的修改版本:https://stackblitz.com/edit/angular-3hceet?file=src%2Fapp%2Fapp.component.ts