2017-03-15 3 views
1

로그인 할 때 로그인 컨트롤러가 있고 성공하면 데이터가 홈 페이지에 표시됩니다. 이 데이터를 집에 전달하는 방법은 무엇입니까? 각도 2의 한 구성 요소에서 다른 구성 요소로 데이터를 전달하는 방법

ngOnInit() { 
    this.returnUrl = '/home'; 
    } 
    doLogin(event) { 
    // console.log(event); 
    // console.log(this.loginForm.value); 
    this.authenticationService.login(this.loginForm.value.username, this.loginForm.value.password) 
    .subscribe(
    (response) => { 
    console.log(response); 
    if(response.authenticateResult==0){ 
    sessionStorage.setItem('user_token', response.user_token); 
    console.log(response.project_list.projects); 
    this.router.navigate([this.returnUrl]); 
    }else{ 
this.error = 'Please enter correct Username and password'; 
    } 
    } 
    ) 
    } 

response.project_list.projects 내가 홈 페이지에 표시 할 프로젝트의 목록이 로그인 구성 요소의 기능입니다. 나는 앵귤러 2에 익숙하지 않다. 그래서 나는 로그인 컴포넌트에있는 데이터에 어떻게 접근 할 수 있는지 이해하지 못하고있다. 1 구성 요소에서 다른 구성 요소로 데이터에 액세스하고 해당 특정 구성 요소에 따라 처리하는 방법이 있습니까?

+1

http://stackoverflow.com을 사용할 수 있습니다./questions/39738974/can-i-emmit-the-event에서 parent-to-child-in-angular2로 데이터를 보낼 수도 있습니다. – ranakrunal9

+0

감사합니다. 나는이 접근법을 시도 할 것이다. –

+0

게시물이 많습니다. [** Input **] (http://stackoverflow.com/questions/42320402/input-not-working-in-angular-2/42320582#42320582) 및 [** localStorage **] (http : //stackoverflow.com/questions/42603319/how-to-store-an-object-of-a-class-type-in-browsers-storage-and-retrieve-it/42603514#42603514) 링크를 클릭하십시오 해피 코딩 :) – Aravind

답변

1

dat을 공유하려면 services을 사용하는 것이 좋습니다 a 구성 요소 사이에.

export class LoginComponent { 
    constructor(private projectsService: ProjectsService) { } 

    ngOnInit() { 
     this.returnUrl = '/home'; 
     } 

     doLogin(event) { 
     // console.log(event); 
     // console.log(this.loginForm.value); 
     this.authenticationService.login(this.loginForm.value.username, this.loginForm.value.password) 
     .subscribe(
     (response) => { 
     console.log(response); 
     if(response.authenticateResult==0){ 
     sessionStorage.setItem('user_token', response.user_token); 
     console.log(response.project_list.projects); 
     this.projectsService.setProjects(response.project_list.projects); 
     this.router.navigate([this.returnUrl]); 
     }else{ 
    this.error = 'Please enter correct Username and password'; 
     } 
     } 
     ) 
     } 
} 

export class HomeComponent { 
    constructor(private projectsService: ProjectsService) { } 

    ngOnInit() { 
     console.log(this.projectsService.projects); 
    } 
} 

업데이트 :

당신은 추가하려면 로컬에서 여행 프로젝트를 저장할 수 있습니다

다음

// replace any to your actual projects type 
@Injectable() 
export class ProjectsService { 
    public setProjects(projects: any) { 
     this._projects = projects; 
    } 

    public get projects(): any { 
     return this._projects; 
    } 

    private _projects: any = null; //or empty array if projects is an array 
} 

을 다음은 모두 로그인 및 홈 구성 요소를 삽입 할 수처럼 당신은 무언가를 만들 수 있습니다

// replace any to your actual projects type 
@Injectable() 
export class ProjectsService { 
    constructor() { 
     const projects: any = localStorage.getItem(this.projectsKey); 
     if (projects) { 
      this._projects = JSON.parse(projects); 
     } 
    } 
    public setProjects(projects: any) { 
     localStorage.setItem(this.projectsKey, JSON.stringify(projects)); 
     this._projects = projects; 
    } 

    public get projects(): any { 
     return this._projects; 
    } 

    private _projects: any = null; //or empty array if projects is an array 
    private readonly projectsKey: string = 'projects_key'; 
} 
+0

그것은 효과가있다. 고맙습니다 .:) –

+0

이 접근법에 문제가 생기면 페이지 새로 고침시 데이터가 손실됩니다. –

+0

답변을 업데이트했습니다. localStorage를 사용하여 프로젝트를 새로 고침 할 수 있습니다. –

0

예, 출력 데코레이터 및 EventEmmiter 클래스 (각도/코어 모두 포함)를 통해이 작업을 수행 할 수 있습니다. 예를 들어, 내 프로젝트 중 하나에서 "valueChanged"출력을 통해 실제 선택 값을 알려주는 select2를 Angular에 사용하고 "valueChanged"이벤트가 실행될 때마다 실행될 "이벤트 처리기"를 만들었습니다. 이 이벤트 핸들러는 출력 이벤트 자체이기도하며 valueChanged 바로 다음에 실행됩니다.이 작업을 수행하여 데이터를 상위 구성 요소로 전달합니다. 필요한 모든 시간에이 방법을 반복 할 수 있습니다.

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

@Component({ 
    selector: 'app-select2item', 
    templateUrl: './select2item.component.html', 
    styleUrls: ['./select2item.component.css'] 
}) 
export class Select2itemComponent implements OnInit { 

    private select2options:S2options; 
    private selected:string; 
    @Output()//this is how you declare a custom "output event" 
    selectedItem = new EventEmitter(); 
    constructor() { } 

    ngOnInit() { 
    this.select2options = {}; 
    this.select2options.ajax={ 
     url:"/item/ajax", 
     dataType: 'json', 
     data: (term)=>{ //console.log(term.term); 
     return {sku:term.term}; 
     }, 
     delay:1000, 
     processResults: (data)=>{ 
      console.log(data); 
      return { 
       results:data.map((item)=>{ 
        return {id:item.id, text:item.name}; 
       }) 
      } 
     } 
    }; 

    } 
//and this is where you define your custom "output event" 
    public currentItem(e:any){ 
    this.selected=e.value; 
    this.selectedItem.emit(this.selected); 
    } 

} 

HTML :

<select2 [options]="select2options" 
(valueChanged)="currentItem($event)"></select2> 

는 (은 이온 팀에 의해 만들어진)이 당신을 도울 것입니다,이 빠른 튜토리얼을 살펴 :

여기에 내 코드

TS입니다 Angular Outputs

관련 문제