Angular

[Angular] 라우터문법 - 동기,비동기 하는방식(rx방식)

이채야채 2022. 6. 19. 19:02

라우터 문법

routerLink를 통하여 a링크 매칭,

현재경로일때 routerLinkActive사용하여 css꾸밀수있다.

routerLinkActiveOptions 설정가능

{exact: true} -> 이게 왜필요하냐면 user/1 user/2 이렇게 뒤에 쿼리가 붙는다면 routerLInktActiveOption이 필요하다

params 설정 및 컴포넌트에서 사용하기

 

  • Routes에 :name과 같이 설정하기
  • 사용하는 컴포넌트에서 ActivatedRoute주입하기
  • 주입된 서비스 이용해서 :name 가져오기
    • 동기
      • snapshot
    • 비동기
      • rx
     

 

위와같이 설정해주면 

developer/mark, developer/sophie를 하면 => 그냥 developer 컴포넌트가 보여지게된다.

 

받아서 보여주는 컴포넌트에서 이제 활성화를 시켜준다.

-> 어디? developer

 

들어오는 인자를 보여주는 방식? 2가지. 동기와 비동기

  • Routes에 :name과 같이 설정하기
  • 사용하는 컴포넌트에서 ActivatedRoute주입하기
  • 주입된 서비스 이용해서 :name 가져오기
    • 동기
      • snapshot
    • 비동기
      • rx

 

developer 컴포넌트의 constructor 안에서 설정해주기

this.route.snapshot.paramMap.get('name');
 
이렇게 꺼내오면 바로 튀어나옴..
얘를 이제 템플릿에 표현해주면된다.

this.name에 할당을 해주고

 

이렇게된다~!

 

 

이제 비동기로 가져와보자

map을 사용할 수 없는 이유는 params => Observable이기에

obeservable의 map을 사용하려면 rx의 map라이브러리를 가져와야한다고한다..

뭔소리야...스벌..ㅠ

 

npm install --save rxjs-compat 설치후, import시켜준다.

예전버전으로하면 안먹음...ㅎㅎ..^^

왜냐?

pipe없이 map쓰는 방식이 사라졌다고함.

 

 

구글링구글링

 

npm install --save rxjs-compat

import { Observable, Observer } from 'rxjs';
import { map } from 'rxjs/operators';

을 사용하고

 

pipe를 활용한다.

 

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Observable, Observer } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-developer',
  templateUrl: './developer.component.html',
  styleUrls: ['./developer.component.css'],
})
export class DeveloperComponent implements OnInit {
  name: Observable<string>;

  constructor(private route: ActivatedRoute) {
    // this.name = this.route.snapshot.paramMap.get('name');
    this.name = this.route.params.pipe(map((p) => p['name']));
  }

  ngOnInit(): void {}
}

그 후에 무.조.건.

 

| async 를 사용해야한다.