2017-04-02 3 views
1

저는 Angular 2 형 스크립트를 배우기위한 초보자입니다. 하나의 구성 요소와 다른 구성 요소간에 데이터를 전달하고 싶습니다.각도 2 유형 스크립트에서 탐색 또는 경로없이 데이터 하나의 구성 요소를 다른 구성 요소에 전달할 수있는 모든 방법은 무엇입니까?

Serives.ts

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

    // Name Service 
    export interface myData { 
     myDataname:any; 
    } 

    @Injectable() 
    export class GetService { 
     sharingData:any={myDataname:"My data string"}; 

     saveData(str:any){ 
      alert("Save Data"); 
     // console.log('save data function called' + JSON.stringify(str)); 
     this.sharingData.myDataname=str; 
     console.log(JSON.stringify(this.sharingData.myDataname)); 
     } 
     getData():any{ 
    console.log('get data function called'); 
    console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s"); 
     return this.sharingData.myDataname; 
} 
    } 

먼저 Component.ts

import { GetService } from '../service/get-service'; 

    @Component({ 
     selector: 'firstcomponent, 
     templateUrl: 'firstcomponent.html', 
     providers:[GetService] 
    }) 

    export class firstcomponentDetails { 
    firstname:string; 
    lastname:string; 

     constructor(public getservice: GetService) { 
     this.getservice= getservice; 

    submitForm(value: any):void{ 
      console.log(' Personal Details Form submited!'); 
     console.log(value); 
     this.getservice.saveData(value); 
    } 
} 
    } 

둘째 Component.ts

import { GetService } from '../service/get-service'; 
    @Component({ 
     selector: 'secondpage', 
     templateUrl: 'secondpage.html', 
     providers: [GetService], 
    }) 
    export class SecondPage { 
    getDatavaluesServices:any; 
    constructor(public getservice:GetService){ 
    this.getservice = getservice; 
    this.getDatavaluesServices=getservice.getData(); 
     console.log(this.getDatavaluesServices); 
    } 
    } 

이것은 내 코드. 이 코드는 첫 번째 구성 요소를 두 번째 구성 요소로 전달했습니다. 문자열 값 my data string에 도착했습니다. 첫 번째 구성 요소 값을 얻는 방법?

+2

https://angular.io/docs/ts/latest/cookbook/component-communication.html –

+0

http://stackoverflow.com/questions/42624053/angular-2-how-interact-between-different-level -components/42624414 # 42624414 여기 이미 대답했습니다. –

답변

0

구성 요소간에 하나의 인스턴스 만 공유되도록 부모 구성 요소 나 모듈별로 서비스를 제공해야합니다. 하위 구성 요소에 providers:[GetService]이 있으면 componet이 인스턴스화 될 때 서비스가 다시 작성됩니다. 따라서 다른 구성 요소가 설정 한 데이터가 손실됩니다.

Parent and children communicate via a service 가이드를 수행 한 경우 하위 구성 요소에는 통신이 수행되는 공유 서비스 공급자가 없지만 mission-control 구성 요소는 my-astronaut과 같이 모든 하위마다 하나의 인스턴스 만 제공합니다.

mission-control 템플릿에서 my-astronaut 구성 요소는 *ngFor 지시어를 통해 여러 번 인스턴스화되었습니다.

충분하지 않은 경우 singleton pattern을 사용하여 서비스에 대한 자체 공급자를 만들 수 있습니다. (구현 방법은 this 대답을 참조하십시오.) 이렇게하면 공급자를 사용하여 모든 구성 요소에 서비스를 제공 할 수 있습니다.

1

서비스를 생성하여 주 모듈로 가져 와서 거기에서 내 보낸 다음이를 사용하려는 구성 요소에 주입 할 수 있습니다.

@Injectable() 
export class StateService { 
    someStateValue: string;; 
} 

이 방법으로 응용 프로그램을 통해 서비스의 인스턴스가있을 것이라는 점을 의미하는 싱글 서비스를 만드는, 그래서 어떤 값을 당신에게 :

import { StateService } from '../../../core/state.service'; 

    constructor(
    @Inject(StateService) private stateSrvc: StateService 
) {} 

서비스는 다음과 같이 될 것입니다 한 구성 요소의 집합을 다른 구성 요소에서 검색 할 수 있으므로 URL 및 라우터 매개 변수를 통해 데이터를 전달하지 않고도 구성 요소간에 데이터를주고받을 수 있습니다.

stateSrvc.someStateValue = 1234 

또는

someLocalVariable = stateSrvc.someStateValue 

을 또는 당신이 할 수있는 : 해당 서비스의 상태 저장을 유지하는 방법

당신까지, 당신은 단순히 위와 같이 변수를 선언하고 얻을 값을 직접 설정할 수있다 getVariablesetVariable은 더 많은 기능을 제어 할 수 있습니다.

Observables and Subjects 또는 BehaviorSubjects를 사용하여 RxJS를 사용하여 상태를 저장할 수도 있습니다.