【问题标题】:Call function from one component to another to update the button从一个组件调用函数到另一个组件以更新按钮
【发布时间】:2018-06-15 05:20:35
【问题描述】:

AuthComponent

    import { TopnavComponent } from './../topnav/topnav.component';
    import { Component, OnInit,ViewContainerRef } from '@angular/core';
    import {AuthService} from "./auth.service";
    import { NgForm } from '@angular/forms';
    import {Router} from "@angular/router";
    import {Profile} from "./auth.model";
    import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs';

    @Component({
        selector: 'app-auth',
        templateUrl: './auth.component.html',
        styleUrls: ['./auth.component.css'],
        providers:[TopnavComponent]
    })
    export class AuthComponent implements OnInit {
    constructor(private authUser: AuthService, private router: Router,public topnav:TopnavComponent) {};
    callMethod() {

           document.cookie = 'uid='+ this.isAuthSuccess.profile[0].guProfileId;
                    document.cookie = 'isInstructor='+ this.isAuthSuccess.profile[0].isInstructor;
                    document.cookie = 'isStudent='+ this.isAuthSuccess.profile[0].isStudent;
                    this.topnav.changeState();
                    this.router.navigateByUrl('/home');
            });
        }
    }

顶部导航组件

import { Component, OnInit } from '@angular/core';
import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Router, ActivatedRoute} from "@angular/router";
import { Observable } from 'rxjs';
import {AuthService} from "../auth/auth.service"

@Component({
    selector: 'app-topnav',
    templateUrl: './topnav.component.html',
    styleUrls: ['./topnav.component.css']
})
export class TopnavComponent implements OnInit {
    hideCourse=false;
    constructor(private router: Router,private auth:AuthService) { }
    changeState(){
        this.hideCourse=!this.hideCourse;
    }
}

TopnavComponent.html

<button (click)="callMethod()">Submit</button>
<ul class="navbar-nav mr-auto" *ngIf="hideCourse">
    <li class="nav-item dropdown">
        <a class="nav-link" routerLink="/auth">Sign In</a>
    </li>
</ul>

我在我的 Angular 2 网站中有上述组件,我在其中调用 callMethod 来做某些事情,然后调用 topnavComponent 的 changeState 来隐藏 Sign导航栏中的 In 按钮。我得到了分配给 *ngIf 的 hideCourse 属性的正确值,但它没有按需要更新视图。

谁能告诉我我的方案的解决方案。

谢谢。

【问题讨论】:

    标签: angular


    【解决方案1】:

    我不会试图去理解你的代码,只是简单的给你代码把一个组件实例注入到另一个组件中(记得导入未知的关键词)。

    constructor(
      @Inject(forwardRef(() => TopnavComponent)) private topnav: TopnavComponent
    )
    

    现在你可以使用了

    this.topnav.changeState();
    

    【讨论】:

    • 你是那个要求它的人,不要告诉我它有多糟糕......这是一种不好的做法,只是因为它在两个组件之间创建了依赖关系,但让我们面对它,你正在创建一个应用程序,你正在启动它,你肯定不会在其他地方使用你的组件。
    • 顺便说一句,您是说当您尝试将一个组件注入另一个组件时。你只是没有代码,所以我提供给你了。
    • @Eliseo 在我的情况下,我得到了价值,但它没有更新视图。
    • 这是一个幸运的镜头,因为没有什么能告诉 Angular 使用哪个组件实例。
    【解决方案2】:

    有很多选项可以让两个组件进行通信。使用服务,我们可以订阅 Observable 或简单地使用 getter。这种方法更符合单独组件的“哲学”。您的组件不需要知道其他组件

    服务

    @Injectable()
    export class UtilCommonService {
    
      sharedData:any;  //<--a public variable that can be changed
      private dataSource = new Subject<any>();
      data = this.dataSource.asObservable();  //<--an Observable
      change(param:any) {   //<--function to force a change
         this.dataSource.next(param)
      }
      constructor() { }
    }
    

    组件-uno

    @Component({
      selector: 'app-app-uno',
      template:`<button (click)="buttonClick()">Push me</button>`
    })
    export class AppUnoComponent implements OnInit {
    
      constructor(private utilCommonService:UtilCommonService) { }
    
      ngOnInit() {
      }
      buttonClick()
      {
        this.utilCommonService.change("Hola mundo"); //<--call to change of the service
        this.utilCommonService.sharedData="Adios mundo"; //<--simply change the value of the variable
      }
    }
    

    组件操作

    @Component({
      selector: 'app-app-dos',
      template:`<p>Data:{{data}}</p>
      <p>Shared Data:{{sharedData}}</p>`
    })
    export class AppDosComponent implements OnInit {
    
      constructor(private utilCommonService: UtilCommonService) { }
      data:any;
      get sharedData() //<--a getter
      {
        return this.utilCommonService.sharedData;
      }
      ngOnInit() {
        this.utilCommonService.data.subscribe((param: any) => { //<--subscribe to an observable
          this.data=param;
        });
      }
    }
    

    AppMain

    @Component({
      selector: 'app-app-main',
      template:`<app-app-uno></app-app-uno>
      <app-app-dos></app-app-dos>`
    })
    export class AppMainComponent{
      constructor() { }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-13
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2017-01-09
      相关资源
      最近更新 更多