2016-11-01 5 views
0

app.component각도이 문제

import { Component, OnInit } from '@angular/core'; 
import { AngularFire } from 'angularfire2'; 
import { Subscription } from 'rxjs/Subscription'; 
import { MainService } from './main.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html' 
}) 
export class AppComponent implements OnInit { 
    private logsub: Subscription; 
    private checking: string; 
    constructor(private af: AngularFire, private mainService: MainService){} 

    ngOnInit(){ 
     this.logsub = this.mainService.userThere$.subscribe(isUser => { 
      if (isUser){ 
       firebase.auth().onAuthStateChanged(function(user){ 
        if (user){ 
         this.mainService.userLogged(true); 
         alert("True"); 
        } 
        else { 
         this.mainService.userLogged(false); 
        } 
       }); 
      } 
     }); 

     if (this.mainService.userLogged){alert("Fish");} 
    } 

    ngOnDestroy(){ 
     this.logsub.unsubscribe(); 
    } 
} 

main.services

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

@Injectable() 
export class MainService { 
    private userThere = new Subject<boolean>(); 
    userThere$ = this.userThere.asObservable(); 

    userLogged(isUser: boolean){ 
     this.userThere.next(isUser); 
    } 
} 

이 내가 여기에 이해하지 오전. 사용자 인증 코드가 있습니다. 사용자가있는 경우 alert("True")이 표시됩니다. 또한 userLogged 구독을 설정했습니다.

내 페이지를로드 할 때 사용자가 없음을 확인할 수 있습니다. 나는 alert("True");을 얻지 못한다. 그러나이 아래에는 테스트 코드 if (this.mainService.userLogged){alert("Fish");}이 포함되어 있습니다.

사용자가 없는데도 불구하고 나는 여전히 물고기에 대해 경고를 받고 있습니다. 즉 (}는 mainService로서

가 컴포넌트에 주사된다

+3

데 도움이 기능으로'userLogged'는 –

+0

그래서 어떻게 내 if 문을 포맷 할 수 정의? – abrahamlinkedin

답변

1

alertif 블록으로서 호출되는 경우에있어서 userLogged가 서비스 mainService

if (this.mainService.userLogged){alert("Fish")에 존재하는지 검사되고 인스턴스화되고 각도 주입기로 구성 요소의 생성자로 전달됨), 정의 된 모든 메소드가 포함됩니다. 타이프 스크립트 클래스은 궁극적으로 입니다. 자바 스크립트 생성자 함수은 인스턴스화시 자바 스크립트 객체을 제공합니다. 이러한 객체는 JS의 첫 번째 클래스 객체를 인식 할 수있는 함수로 속성을 가질 수 있습니다.

그래서 위의 userLoggedmainService에 정의 된대로, this.mainService.userLogged 당신이 truthy 값을 받고 확인 블록의 경우. 따라서 if 블록으로 들어가고 alert이 (가) 해고되고 있습니다.

편집 : 의견을 바탕으로

내가 무엇을 수집하는 것은 당신이 사용자 정보가 mainService.userThere$ 관찰자 스트림을 통해 도달 할 때 추가 로직을 작성 할 수 있도록하려는 것입니다. 단일 관찰자 스트림에 대해 여러 콜백을 사용할 수 있습니다. 관찰자 소스가 트리거되면 관찰자 스트림에 등록한 모든 콜 백이 호출됩니다. 그래서 당신은이 작업을 수행 할 수 있습니다

ngOnInit(){ 
    this.logsub = this.mainService.userThere$.subscribe(isUser => { 
     if (isUser){ 
      firebase.auth().onAuthStateChanged(function(user){ 
       if (user){ 
        //this.mainService.userLogged(true); 
        alert("True"); 
        // no need to set userLogged true or false again 
       } 
       else { 
        //this.mainService.userLogged(false); 
       } 
      }); 
     } 
    }); 

//if (this.mainService.userLogged){alert("Fish");} 
// instead of above do this 
this.mainService.userThere$.subscribe(isUser => { 
    alert("Fish"); 
    // We can attach as many functions as we want to the 
    // observer stream. So all you have to do is simply pass 
    // userThere$ observer stream in any component you want to 
    // write the additional logic 
}) 



} 

희망이 truthy 될 것 this.mainService.userLogged` 물론`의

+0

예. 돌이켜 보면 말이 되네. 그렇다면 어떻게 if 문을 포맷 할 수 있을까요? 'this.mainService.userLogged = true'로 변경하면 변경되지 않습니다. – abrahamlinkedin

+1

자, 여기서 당신이하고 싶은 것을 이해하도록하겠습니다. 기본적으로 사용자가있을 때 경고를 발생시키고 자합니다. 나 맞아 ? –

+0

내가 원하는 것은 모든 구성 요소에서 if 조건으로 해고 될 수있는 서비스를 설정하는 것입니다. 그래서'userLogged'라면 내 구성 요소 (app 또는 무엇이든)가'x'을 할 수있게 허용하십시오. – abrahamlinkedin