본문 바로가기

Javascript/Angular

component 끼리 통신하기

상황


app.component.ts 에서 라우팅 되는 페이지들의 데이터를 받아서 처리해야할때



잘못 구현 된걸 수도 있는데 이런게 있다면 보심 될것같음


base.service.ts 서버스를 만들고 app.module에등록한다.


import { Output, EventEmitter, Injectable } from '@angular/core';

import { BehaviorSubject } from "rxjs/Rx";


@Injectable()

export class BaseService {

   @Output() asideVisible = new BehaviorSubject<Boolean>(true);

   @Output() tabNumber = new BehaviorSubject<number>(2);


   setAside(input: Boolean) {

        this.asideVisible.next(input);

        //this.asideToggle.emit(input);

    }

    setTab(input: number)

    {

        this.tabNumber.next(input);

    }

}



app.component.html 파일 내용이다


<app-aside [isAsideOpen]="isAsideOpen"></app-aside>

<router-outlet></router-outlet>

<app-footer [tab]="tab"></app-footer>



app.component.ts 파일 내용이다.


import { Component,OnInit } from '@angular/core';

import { BaseService } from './services/base.service';

import * as $ from 'jquery';

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html'

})

export class AppComponent implements OnInit {

    tab: number = 0;

    isAsideOpen: boolean = true;

    title = '상상파크';

    constructor(private baseService: BaseService) {


    }


    ngOnInit() {

        this.baseService.asideVisible.subscribe((visible: boolean) => {//Aside

            this.isAsideOpen = visible;

        });

        this.baseService.tabNumber.subscribe((num: number) => {//Tab

            this.tab = num;

        });

    }

    onAsideOpenChanged(input: boolean) {

        this.isAsideOpen = input;

    }


    onTabChanged(input: number)

    {        

        this.tab = input;

    }

}






간단히 설명하자면 app.component에서  이벤트 리스팅을 한다


그리고 라우팅된 페이지에서 



feed-list.component.ts 에서


import { Component, OnInit, ViewChild, EventEmitter, Output } from '@angular/core';

import { BaseComponent } from '../base/base-component.component';



@Component({

    selector: 'app-feed-list',

    templateUrl: './feed-list.component.html'

})

export class FeedListComponent  implements OnInit { 


    constructor(public baseConfig:BaseService) {    

    

        

    }


    ngOnInit() {        

        this.baseConfig.asideVisible(true);

    

    }   

}


위와같이 서버스에 등록된함수를호출하면 된다.