【问题标题】:How to call a function of one component in another如何在另一个组件中调用一个组件的功能
【发布时间】:2016-10-26 13:09:02
【问题描述】:

我有 2 个组件导航栏和登录,我想在登录组件的导航栏中调用一个函数,到目前为止我尝试了这个但没有成功...... 我的 navbar.ts,

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

@Component({
    selector: 'header-Navbar',
    templateUrl: './app/navbar/navbar.html',
})
export class Navbar implements OnInit  {

    constructor(public router: Router) {

    } 
    get(){
         if (this.user == null) {
            this.showstartupbuttons = true;
            this.showsicons = false;
        }
        else {
            this.username = this.user.username;
            this.showsicons = true;
            this.showstartupbuttons = false; 
        }
    }

我的 login.ts,

import {Component, OnInit} from '@angular/core';
@Component({
    templateUrl: './app/login/login.html',
    providers:[Navbar]
})
export class Login implements onInit{
    ckeditorContent:any;
    constructor(public navbar:Navbar) {}
      ngOnInit(){
           this.navbar.get();
      }

我使用了提供程序,但我不确定这些过程。任何人都可以建议帮助。

【问题讨论】:

  • 请参阅我的问题 - stackoverflow.com/questions/40219356/… 它的调用属性,但您可以以相同的方式调用函数。不幸的是,我遇到了一个没有解决的问题。也许你知道

标签: angular typescript


【解决方案1】:

您可以将服务用于这样的组件交互。

import { Subject }    from 'rxjs/Subject';
import { Injectable } from '@angular/core';

@Injectable()
export class NavbarService{
    private getSource = new Subject<any>();
    get$ = this.getSource.asObservable();

    triggerNavbarGet(){
        this.getSource.next(null);
    }
}

您需要将此服务注入到导航栏和登录。请记住,每个提供者的服务都是单例的。所以这个服务需要由一个同时包含导航栏和登录的组件来提供。

在您的导航栏组件上:

constructor(public router: Router, navbarService: NavbarService) {
    navbarService.get$.subscribe(param => {this.get();})
}

您可以在您的登录组件上触发此功能,例如

constructor(public navbar:Navbar, private navbarService: NavbarService) {}
      ngOnInit(){
           this.navbarService.triggerNavbarGet();
      }

更多关于组件交互here

【讨论】:

  • 但我不能将@injectable() 保留在我的导航栏组件中,因为它是一个组件
  • 您只需要在服务中添加@Injectable()。不要将其添加到组件中。您还可以删除登录组件上的providers:[Navbar]。我的解决方案不需要它。
  • 实际上我的导航栏是一个组件,要在我的 login.ts 中使用它,我必须将@Injectable 放入它,但它是一个组件......。还有其他方法吗?
  • 我知道你的导航栏是一个组件。你应该为它创建一个服务。在我的回答中,我为您创建了一个名为 NavbarService 的服务。请阅读我答案末尾的文档。
猜你喜欢
  • 2017-03-30
  • 2019-07-26
  • 2011-01-11
  • 2019-04-11
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 2017-03-11
相关资源
最近更新 更多