2017-11-22 14 views
2

ngIf가 관찰 결과를 선택하는 데 약간의 문제가 있습니다. 두 가지 구성 요소가 있는데 하나의 구성 요소가 다른 구성 요소에 콘텐츠를 표시하거나 표시하지 않게하려고합니다.Ng가 관찰 가능과 함께 작동하지 않습니다.

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

consumerComponent.html

 <p> 
     consumer works! 
    </p> 

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

내가 슬라이더 클릭하면

 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>  

지금 값이 변경되어 app.modules.ts 가치가 변했지만, ngif를 사용하는 소비자 구성 요소가 어떤 이유로 온/오프 토글을하지 않는다는 것을 알기를 기대하면서 콘솔 출력을 얻습니다. 내가 기대했던 것처럼. 나는 뭔가를 빠뜨린 것 같고 아마도 매우 쉬운 해결책이긴하지만 일주일 동안 해결책을 찾고 있었고 나는이 질문을 게시 할 것이라고 생각했다. 누군가 내가 잘못 가고있는 조언을 할 수 있는지 알아보기. 모든 조언과 도움에 미리 감사드립니다. 이 같은

+0

우리가 작업 할 수있는 플 런커를 만들 수 있습니다. 또는 (소비자와 같은) 더 많은 로그 문을 추가하고 문제가 어디에 위치하는지 확인할 수 있습니다. – DeborahK

+0

어디서 관찰 할 수 있습니까? – Ced

+0

코드가 잘 작동합니다 [Plunkr] (https://plnkr.co/edit/SjhNK4flB53I2bB8ywDh). –

답변

0

시도 비동기 파이프 :

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

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


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

이 있습니다

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> 
1

나는 비동기 파이프를 사용하는 것이 좋습니다 몇 가지 이유로, 하나는 클리너이며 비동기 작업을 처리합니다. 두 번째는 비 멤버 파이프가 비공개 파이프 라인을 제거하기 때문에 실제로 컴포넌트가 메모리 누수가 있다는 것입니다.

또한이를 제거하는 것이 좋습니다 것 :

public source:boolean = true; 

을 서비스에서. 그것이 상태이며, 버그의 원인이며 불필요합니다. 이 서비스의 소비자는 항상 관찰 대상을 사용해야합니다. 이와 같은 동기식 및 비동기식 작업을 혼합하는 습관을 갖게되면 두통을 겪게됩니다.

0

감사합니다. 실제로 모든 사람은 샘플 코드를 게시 했으므로 실제 오류가 발생했습니다. 서비스 제공 업체는 app.modules뿐 아니라 구성 요소에도 포함되어있었습니다. 제안 된대로 비동기 파이프를 추가했지만 모두 다시 작동하지 않습니다. 그래서 나는 그것을 제거했습니다.