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

Angular - 튜토리얼10_데이터 공유(Share, Inject)

zoaseo 2022. 9. 29. 10:31

1)

MyType.ts 추가

MyType.ts

export declare type INFORMATION = { // 전달할 데이터 형식
    data1 : string,
    data2 : number,
    data3 : any,
};

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

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

import {INFORMATION} from './MyType';

const myData : INFORMATION = {
  data1 : 'data1',
  data2 : 1433,
  data3 : ['data3_1','data3_2'],
}

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule, FormsModule
    ,ReactiveFormsModule
  ],
  providers: [
    {provide:'sending_name',useValue:myData} // 제공? 사용값?
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

provider: [

    {provide:'이름',useValue:사용값}

],

 

2)

login.component.ts

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

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);
   }

  ngOnInit(): void {
  }

  styleArray = {'wrong_id':false, 'wrong_pwd':false};
  
  tryToLogin() : void {
    if(this.id == 'admin' && this.pwd == '1234'){
      alert('로그인합니다!');
      this.visible1 = true;
      this.sendMyEvent.emit(this.visible1); // app컴포넌트에 전달
    } 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, this.visible1);
  }

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

 

app.component.html 부분 수정
login.component.ts 생성자(constructor) 부분 Inject 사용