개발이 좋아서/Angular가 좋아서

Angular - 튜토리얼11_Observable

zoaseo 2022. 9. 29. 11:17

1) 단순하게 데이터만 전달(Injection) 하였던 것이 서비스라는 클래스(Class)형태로 전달할 수 있음!

*경로 잘 보기!

ng g service myService

my-service.service.ts

import { Injectable } from '@angular/core';
import { INFORMATION } from './MyType';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  public readonly myData : INFORMATION = {  //내가 전달할 데이터
    data1 : 'data1',
    data2 : 1433,
    data3 : ['data3_1','data3_2']
  };

  constructor() { 

  }
}

app.module.ts

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

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

import {FormsModule} from '@angular/forms';
import { DashboardComponent } from './dashboard/dashboard.component'; 
import { ReactiveFormsModule } from '@angular/forms'; 

import { MyServiceService } from './my-service.service';  //서비스 클래스 추가

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule, FormsModule, ReactiveFormsModule 
  ],
  providers: [
    MyServiceService  //MyServiceService를 제공하도록 합니다.
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

login.component.ts

//..생략
import { MyServiceService } from '../my-service.service';
export class LoginComponent implements OnInit {
  //..생략
  constructor(service : MyServiceService) { 
    console.log(service)
  }
  //..생략
}

 

2) 이제부터 어렵다!!!

my-service.service.ts

import { Injectable } from '@angular/core';
import { INFORMATION } from './MyType';

import { BehaviorSubject, Observable } from 'rxjs'; // 추가!

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {
  public readonly myData : INFORMATION = { // 내가 전달할 데이터
    data1 : 'data1',
    data2 : 1433,
    data3 : ['data3_1','data3_2']
  }
  constructor() { }

  private FACTORY : BehaviorSubject<any> = new BehaviorSubject({});  //??
  public readonly TV: Observable<any> = this.FACTORY.asObservable();  //??????

  public addData(arg : boolean, loginInfomation? : any) : void{
    if(arg){
      this.FACTORY.next(loginInfomation);  //????
    } 
  }

}

login.component.ts

import { Component, OnInit, Input, Output, EventEmitter, Inject } from '@angular/core';
import { FormControl, Validators } from '@angular/forms'; // 추가!
import { MyServiceService } from '../my-service.service'; // 추가!

// import { INFORMATION } from '../MyType';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // @Input() visible1! : boolean; // 받는 역할
  // @Output() sendMyEvent : EventEmitter<any> = new EventEmitter(); // 보내는 역할
  id:any = new FormControl('');
  pwd:any = new FormControl('',[Validators.required, Validators.minLength(4)]);
  private message :any;

  // constructor(@Inject("sending_name") my_type : INFORMATION) {
  //   console.log(my_type);
  //  }
  constructor(private service : MyServiceService){ // private 제어자를 붙여서 클래스 내부에서 사용가능하게 합니다.
    console.log(service);
  }

  ngOnInit(): void {
  }

  styleArray = {'wrong_id':false, 'wrong_pwd':false};
  
  tryToLogin() : void {
    // this.service.addData(true, {id:'admin', name:'사용자'}); // 서비스에 addData 함수를 호출합니다.
    if(this.id.value == 'admin' && this.pwd.value == '1234'){
      alert('로그인합니다!');
      // this.visible1 = true;
      // this.sendMyEvent.emit(this.visible1); // app컴포넌트에 전달
      this.service.addData(true, {id:'admin', name:'사용자'}); // 서비스에 addData 함수를 호출, 로그인 성공값을 전달합니다.
    } else if(this.id != 'admin') {
      this.setMessage = 'wrong id';
      this.styleArray.wrong_id = true;
      this.styleArray.wrong_pwd = false;
    } else if(this.pwd != '1234') {
      this.setMessage = 'wrong pwd';
      this.styleArray.wrong_id = false;
      this.styleArray.wrong_pwd = true;
    }
    console.log(this.id, this.pwd);
  }

  // set과 get이라는 명령어(예약어)는 함수를 마치 속성을 다루듯이 사용할 수 있게 해주는 기능입니다.
  set setMessage(arg:string) { // 대입합니다.
    this.message = arg;
  }
  get getMessage() : string{ // 가져옵니다.
    return this.message;
  }
}

app.component.ts

import { Component } from '@angular/core';
import { MyServiceService } from './my-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  loginBool = true;
  boardBool = false;

  constructor(private service : MyServiceService) {
    service.TV.subscribe(arg=>{
      if(arg && arg.id){
        console.log('로그인이 성공했군요 :',arg);
        this.loginBool = false;
        this.boardBool = true;
      }
    })
  }
  //@ts-ignore
  // getEventThanks(event) {
  //   console.log(event);
  //   if(event == true){
  //     this.loginBool = false;
  //     this.boardBool = true;
  //   }
  // }
}

3)

login.component.ts

import { Component, OnInit, Input, Output, EventEmitter, Inject } from '@angular/core';
import { FormControl, Validators } from '@angular/forms'; // 추가!
import { MyServiceService } from '../my-service.service'; // 추가!

// import { INFORMATION } from '../MyType';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // @Input() visible1! : boolean; // 받는 역할
  // @Output() sendMyEvent : EventEmitter<any> = new EventEmitter(); // 보내는 역할
  id:any = new FormControl('');
  pwd:any = new FormControl('',[Validators.required, Validators.minLength(4)]);
  private message :any;

  // constructor(@Inject("sending_name") my_type : INFORMATION) {
  //   console.log(my_type);
  //  }
  constructor(private service : MyServiceService){ // private 제어자를 붙여서 클래스 내부에서 사용가능하게 합니다.
    console.log(service);
  }

  ngOnInit(): void {
  }

  styleArray = {'wrong_id':false, 'wrong_pwd':false};
  
  tryToLogin() : void {
    // this.service.addData(true, {id:'admin', name:'사용자'}); // 서비스에 addData 함수를 호출합니다.
    if(this.id.value == 'admin' && this.pwd.value == '1234'){
      alert('로그인합니다!');
      // this.visible1 = true;
      // this.sendMyEvent.emit(this.visible1); // app컴포넌트에 전달
      this.service.addData(true, {id:'admin', name:'사용자'}); // 서비스에 addData 함수를 호출, 로그인 성공값을 전달합니다.
    } else if(this.id != 'admin') {
      this.setMessage = 'wrong id';
      this.styleArray.wrong_id = true;
      this.styleArray.wrong_pwd = false;
    } else if(this.pwd != '1234') {
      this.setMessage = 'wrong pwd';
      this.styleArray.wrong_id = false;
      this.styleArray.wrong_pwd = true;
    }
    console.log(this.id, this.pwd);
  }

  // set과 get이라는 명령어(예약어)는 함수를 마치 속성을 다루듯이 사용할 수 있게 해주는 기능입니다.
  set setMessage(arg:string) { // 대입합니다.
    this.message = arg;
  }
  get getMessage() : string{ // 가져옵니다.
    return this.message;
  }
}

app.component.html

<app-login *ngIf="loginBool"></app-login>
<app-dashboard *ngIf="boardBool"></app-dashboard>

app.component.ts

import { Component } from '@angular/core';
import { MyServiceService } from './my-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  loginBool = true;
  boardBool = false;

  constructor(private service : MyServiceService) {
    service.TV.subscribe(arg=>{
      if(arg && arg.id){
        console.log('로그인이 성공했군요 :',arg);
        this.loginBool = false;
        this.boardBool = true;
      }
    })
  }
  //@ts-ignore
  // getEventThanks(event) {
  //   console.log(event);
  //   if(event == true){
  //     this.loginBool = false;
  //     this.boardBool = true;
  //   }
  // }
}

 

댓글수0