Ng如果不使用可观察的

时间:2017-11-22 22:24:24

标签: angular observable angular-ng-if

我在使用ngIf获取可观察量方面遇到了一些问题。我有两个组件,我试图让一个组件导致另一个组件显示或不显示内容。

filterComponent.ts

    import { Component, OnInit } from '@angular/core';
    import{Observable } from "rxjs";
    import {FilterDataService} from "./filter-data.service";
    import {FormsModule} from "@angular/forms";



    @Component({
      selector: 'app-filter',
       templateUrl: './filter.component.html',
       styleUrls: ['./filter.component.css']   
     })
    export class FilterComponent implements OnInit {
      show: boolean;
       constructor(private filterData: FilterDataService) { }

       ngOnInit() {

         this.filterData.currentSource.subscribe(show => this.show =show);
         this.changeShowFlag(true);
       console.log('Filter Show is ' + this.show);

      }

       changeShowFlag(showFlag:boolean) {
         this.filterData.changeSource(showFlag);
         console.log("current show value " + showFlag);
         console.log("value of show confirmed as "+ this.show);
         console.log("value in service for source " +  this.filterData.source);
          }
         }

filterComponent.html

     <p>
           filter works!
    </p>
     <div class ="toggles">
     <div class="toggle-border">
        <input [(ngModel)]="show"  
          (click)="changeShowFlag(!show);" type="checkbox" id="one" />
        <label for="one">
          <div class="artHandle"></div>
        </label>
      </div>
    </div>

filterDataService.ts

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


     @Injectable()
     export class FilterDataService {
       private _Source = new BehaviorSubject<boolean>(true);
       public source:boolean = true;
       currentSource = this._Source.asObservable();
      constructor() { }

      changeSource(sourceFlag: boolean) {
       this._Source.next(sourceFlag);
       this.source = sourceFlag;
      }


    }

consumerComponet.ts

     import { Component, OnInit } from '@angular/core';
     import { FilterDataService} from "../filter/filter-data.service";

    @Component({
      selector: 'app-consumer',
      templateUrl: './consumer.component.html',
      styleUrls: ['./consumer.component.css']   
    })
    export class ConsumerComponent implements OnInit {
       source: boolean;
       constructor(private filterData: FilterDataService) { }

      ngOnInit() {
         this.filterData.currentSource.subscribe(source  => this.source  = source   );
     }

    }

consumerComponent.html

     <p>
        consumer works!
     </p>

     <div *ngIf="source" >
       show  is on
     </div>

app.modules.ts

     import { BrowserModule } from '@angular/platform-browser';
     import { NgModule } from '@angular/core';

     import { AppComponent } from './app.component';
     import { FilterComponent } from './filter/filter.component';
     import { ConsumerComponent } from './consumer/consumer.component';
     import {FilterDataService} from "./filter/filter-data.service";
     import {FormsModule} from "@angular/forms";

     @NgModule({
       declarations: [
         AppComponent,
         FilterComponent,
         ConsumerComponent
      ],
       imports: [
        BrowserModule,
        FormsModule
      ], 
      providers: [FilterDataService],
       bootstrap: [AppComponent]
     })
      export class AppModule { }

app.component.html

      <div>
        <app-filter></app-filter>
     </div>
     <div>
         <app-consumer></app-consumer>
    </div>    

现在,如果我单击滑块,则更改值并获得控制台输出,以告诉我值已更改但由于某种原因,使用ngif的使用者组件不会打开和关闭。正如我本来期望的那样。我确定我错过了一些东西,这可能是一个非常简单的解决办法,但我一直在寻找一个星期的解决方案,并且我想发布这个问题。看看是否有人可以在我出错的地方提出建议。提前感谢您的任何建议和帮助。

3 个答案:

答案 0 :(得分:3)

我建议使用异步管道:

source$: Observable<boolean>;
constructor(private filterData: FilterDataService) { }

ngOnInit() {
    this.source$ = this.filterData.currentSource;
}


<div *ngIf="source$ | async" >
    show  is on
</div>

有几个原因,一个是更清洁并为您处理异步操作。第二个是你的组件实际上有内存泄漏,因为你没有取消订阅,异步管道为你清理那些。

还建议你删除它:

public source:boolean = true;

来自您的服务。这是状态,它是错误的来源,是不必要的。此服务的消费者应始终使用observable。如果养成混合这种同步和异步操作的习惯,你会遇到麻烦。

答案 1 :(得分:0)

尝试像这样的异步管道:

export class ConsumerComponent implements OnInit {
   source: Observable<boolean>;
   constructor(private filterData: FilterDataService) { }

  ngOnInit() {
     this.source = this.filterData.currentSource;
 }

并在视图中以这种方式使用

<div *ngIf="source | async" >
   show  is on
 </div>

答案 2 :(得分:0)

谢谢,每个人我实际上只发布了示例代码我发现我的实际错误我已经在组件中包含了服务提供程序以及app.modules。 我已经按照建议添加了异步管道,但之后它又停止了工作。所以我已将其删除了。