首页 > 解决方案 > 从不同的组件更改变量值 - Angular 4

问题描述

我有两个组件,一个是home.component,一个是loading.component(加载屏幕)。载入画面有倒计时,倒计时之后,他做点什么。我需要做的是使加载屏幕能够自定义倒计时长度。我尝试使用 EventEmiter,但它不起作用。

home.component.html:

<a (click)="applyChanges()" class="green" style="margin-left: 8px; cursor: pointer"><i style="margin-right: 5px;"class="fa fa-check"></i>Apply changes now</a>

home.component.ts

@Output() loadingScreenStart: EventEmitter<any> = new EventEmitter();


applyChanges(){
this.dashboard.applyChanges().catch(
  err => {
    console.log("There was an error: "+err.status);
    console.log("There was an error: "+err.statusText);
    //this.handleError(err);
    return Observable.throw(err);
  }
)
.subscribe(
  data => {
    this.loadingScreenStart.emit(34);
    this.router.navigate(['/loading']);
  }
);

加载.component.html

<div class="container container-table" (loadingScreenStarted)="onScreenStart($event)">
  <div class="row vertical-10p">
    <div class="container">
      <img src="../../assets/img/LoginLogo.png" class="center-block logo">
      <img style="width: 15em"  src="../../assets/img/gears.svg" class="center-block ">
      <div class="text-center col-sm-6 col-sm-offset-3">
        <h1>Changes are taking place</h1>
        <h4>You will be redirected in {{timeLeft}} seconds</h4>
      </div>
    </div>
  </div>

加载.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { AuthGuard } from '../guard/auth.guard';
import { Title } from '@angular/platform-browser';
@Component({
  selector: 'app-loading',
  templateUrl: './loading.component.html',
  styleUrls: ['./loading.component.css']
})
export class LoadingComponent implements OnInit {
   public timeLeft;
   public intervalId;
   constructor(public titleService: Title, public guard: AuthGuard) { }
   onScreenStart(length) {
      this.timeLeft = length;
      console.log(length);
   }
   ngOnInit() {
      this.titleService.setTitle("Loading... | something);
      this.startCounter();
      localStorage.removeItem('statusInfo');
   }
   startCounter() {
      this.intervalId = setInterval(() => {
         if (this.timeLeft == 1) {
            clearInterval(this.interValId);
         }
         this.timeLeft--;
      }, 1000)
   }
}

标签: htmlangulareventemitter

解决方案


由于这两个组件不是父/子关系,我认为您无法成功使用 EventEmitter。主要问题是您不能同时依赖这两个组件。

因此,针对您的情况的两种常见选择是:

  1. 在路由参数中传递数据(例如https://angular.io/tutorial/toh-pt5#navigating-to-hero-details

  2. 通过共享服务进行通信(例如https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service


推荐阅读