2017-03-03 3 views
2

사용자가 계정을 만들 수있는 양식이 있습니다. 사용자가 제출 버튼을 클릭하면 사용자는 작성한 계정의 세부 정보가있는 다른 페이지로 이동합니다. 내가 겪고있는 문제는 해당 개체를 세부 정보보기로 전달하는 것입니다. 예를 들어각도 2 다른 구성 요소에 양식 데이터 전달하기

여기 형태에 대한 내 구성 요소, 여기

import {Component, OnInit, OnDestroy, Input} from '@angular/core'; 
import { FormGroup, FormBuilder, Validators } from '@angular/forms'; 
import {Customer} from "../model/customer"; 
import {Router } from '@angular/router'; 
import {CustomerService} from "../service/customer.service"; 
import {CustomerProfileComponent} from "../customer-profile/customer-profile.component"; 

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

    @Input() customer: Customer; 

    //this is only dev data do not use this in prod 
    private countries = []; 
    private customerSources = []; 
    private secondarySources =[]; 

    //Create the forum group 
    public newCustomerForm: FormGroup; 
    public submitted: boolean; // keep track on whether form is submitted 

    constructor(private fb: FormBuilder, public customerService: CustomerService,private router: Router) { 

    this.countries = [ 
     {value:'UK'}, 
     {value:'Germany'}, 
     {value:'Turkey'}, 
     {value:'Italy'} 
     ]; 

    this.customerSources = [ 
     {value: 'Through a friend or colleague (not a Client)'}, 
     {value: 'Through an existing Client'}, 
     {value: 'Direct Sales (e.g. cold call, direct mail, email)'}, 
     {value: 'Web Search e.g. Google'} 
    ]; 

    this.secondarySources = [ 
     {value: '1st Hire'}, 
     {value: 'A Test Client With A Long Business Name'}, 
     {value: 'Abbigail West'} 
    ]; 
    } 

    ngOnInit() { 
    this.newCustomerForm = this.fb.group({ 
     id:[''], 
     company_name: ['', [<any>Validators.required, <any>Validators.minLength(5)]], 
     vat:[''], 
     address:[''], 
     country:[''], 
     first_name:[''], 
     surname:[''], 
     phone:[''], 
     email:['',[<any>Validators.required, <any>Validators.minLength(5)]], 
     customer_sources:[''], 
     secondary_sources:[''] 
    }); 
    } 

내 양식의 HTML은,

<form [formGroup]="newCustomerForm" novalidate (ngSubmit)="saveNewCustomer(newCustomerForm.value, newCustomerForm.valid)"> 
    <section> 
     <aside> 
     <p>Once you've added your new <b>Client</b>, you can come back and allow them access to view their <b>Invoices</b> &amp; <b>Payments</b> - they can also make <b>Payments</b> via Paypal if you have it enabled.</p> 
     </aside> 


     <input type="hidden" name="id" formControlName="id"/> 

     <h4>New Client Details</h4> 
     <md-input-container> 
     <input mdInput type="text" name="company_name" placeholder="Customer Name" formControlName="company_name" /> 
     <small [hidden]="newCustomerForm.controls.company_name.valid || (newCustomerForm.controls.company_name.pristine && !submitted)"> 
      Customer Name is required (minimum 5 characters). 
     </small> 
     </md-input-container> 

     <md-input-container> 
     <input mdInput type="text" name="vat" placeholder="VAT Number" formControlName="vat"/> 
     </md-input-container> 

     <md-input-container> 
     <input mdInput type="text" name="address" placeholder="Address" formControlName="address" /> 
     </md-input-container> 

     <md-select placeholder="Country" name="country" formControlName="country" > 
     <md-option *ngFor="let country of countries" [value]="country.value" > 
      {{country.value}} 
     </md-option> 
     </md-select> 

     <h4>Your Primary Contact</h4> 
     <div class="left-column"> 
     <md-input-container> 
      <input mdInput type="text" name="first_name" placeholder="First Name" formControlName="first_name" /> 
     </md-input-container> 
     </div> 

     <div class="left-column"> 
     <md-input-container> 
      <input mdInput type="text" name="surname" placeholder="surname" formControlName="surname" /> 
     </md-input-container> 
     </div> 

     <div class="clearfix"></div> 

     <div class="left-column"> 
     <div class="left-column"> 
      <md-input-container> 
      <input mdInput type="text" name="phone" placeholder="Phone" formControlName="phone"/> 
      </md-input-container> 
     </div> 
     </div> 

     <div class="right-column"> 
     <div class="left-column"> 
      <md-input-container> 
      <input mdInput type="text" name="email" placeholder="Email" formControlName="email"/> 
      <small [hidden]="newCustomerForm.controls.email.valid || (newCustomerForm.controls.email.pristine && !submitted)"> 
       Email is required (minimum 5 characters). 
      </small> 
      </md-input-container> 
     </div> 
     </div> 

     <div class="clearfix"></div> 
     <h4>Customer Source</h4> 
     <div class="left-column"> 
     <md-select placeholder="How were you introduced to this Client?" formControlName="customer_sources"> 
      <md-option *ngFor="let cs of customerSources" [value]="cs.value" > 
      {{cs.value}} 
      </md-option> 
     </md-select> 
     </div> 

     <div class="right-column"> 
      <md-select placeholder="Which Client introduced you?" formControlName="secondary_sources"> 
      <md-option *ngFor="let ss of secondarySources" [value]="ss.value" > 
       {{ss.value}} 
      </md-option> 
      </md-select> 
     </div> 
     <div class="clearfix"></div> 
    </section> 

    <aside> 
     <div class="right-aside"> 
     <button type="submit" class="cancel">Cancel</button> 
     <button type="submit" class="save">Save</button> 
     </div> 
     <div class="clearfix"></div> 
    </aside> 
    </form> 

고객 서비스 내 app.module에서입니다. 여기서는 데이터를 저장하고 사용자를 새 페이지로 이동합니다.

saveNewCustomer(customer: Customer, isValid: boolean){ 
    if(isValid){ 
     this.submitted = true; // set form submit to true 
     this.customerService.saveNewCustomer(customer) 
     .subscribe(
      res => this.customer, 
      error => console.log(<any>error) 
     ); 

     this.router.navigateByUrl('/earning/customers/profile'); 
    } 
    } 


} 

그리고 이것은 고객 개체가보기에 표시되도록 사용하려는 구성 요소입니다.

import {Component, OnInit, Input} from '@angular/core'; 
import {Customer} from "../model/customer"; 
import {NewCustomerComponent} from "../new-customer/new-customer.component"; 

@Component({ 
    selector: 'app-customer-profile', 
    templateUrl: './customer-profile.component.html', 
    styleUrls: ['./customer-profile.component.css'], 
    providers:[NewCustomerComponent] 
}) 
export class CustomerProfileComponent implements OnInit { 

@Input() customer: Customer; 

    constructor() { 
    console.log(this.customer); 
    } 

    ngOnInit() { 
    } 

} 

<main> 
    <header> 
    <h4>&nbsp;</h4> 
    <h1><strong><i></i>Customer profile</strong></h1> 
    </header> 
    <article> 
    <section> 
     <p></p> 

     <p> 
     {{customer}} 
     </p> 
     </section> 
    </article> 
    </main> 

고객은 CustomerProfileComponent에서 정의되지 않았습니다. 내가 뭘 잘못하고 있는지 모르겠다. 누군가가 올바른 방향으로 나를 가리킬 수 있다면 크게 감사하겠습니다.

업데이트

import { Injectable } from '@angular/core'; 
import {Http, Response, Headers, RequestOptions} from '@angular/http'; 
import {CookieService} from "angular2-cookie/services/cookies.service"; 

import {Observable, Subject} from "rxjs"; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 
import {Customer} from "../model/customer"; 


@Injectable() 
export class CustomerService { 

    private csrfToken; 
    private newCustomerUrl = "/earning/customers/new"; 
    private customer = new Subject<Object>(); 

    customer$ = this.customer.asObservable(); 

    constructor(public http: Http, private cookieService: CookieService) { 
    this.getCsrfToken(); 
    } 

    getCsrfToken(){ 
    this.csrfToken = this.cookieService.get("PLAY_SESSION").substring(this.cookieService.get("PLAY_SESSION").indexOf("csrfToken")); 
    } 

    saveNewCustomer(customer:Customer): Observable<Customer>{ 

    let headers = new Headers({ 
     'Content-Type':'application/json' 
    }); 

    let options = new RequestOptions({ headers: headers }); 

    return this.http.post(this.newCustomerUrl+"?"+this.csrfToken, customer, options) // ...using post request 
     .map((res:Response) => res.json()) // ...and calling .json() on the response to return data 
     .catch(this.handleError); //...errors if any 
    } 

    private handleError (error: Response) { 
    return Observable.throw('Internal server error: ' + error); 
    } 

    emitCustomer(customer) { 
    this.customer.next(customer); 
    } 


} 
+0

후 관련 템플릿 코드 –

+0

어느 당신의'html' 코드를 붙여 넣거나가 여기에 표시된 구성 요소 사이의 통신 서비스를 설정 : https://angular.io /docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service –

+0

@AvinashRaj 내 HTML 코드에 붙여 넣었습니다. 감사합니다 –

답변

1

로 공유 서비스가 좋은 옵션이 될 것이라고 언급 한 제안에 따라 서비스 클래스를 포함합니다. 다음의 예는 서비스를 통해 구성 요소 사이의 개체를 공유 :

서비스 :

public sharedCustomer = {}; 

그리고 구성 요소, 당신은 API에서 고객을받은 그 후이 서비스에 고객을 밀어 :

를 내가 가입뿐만 아니라 내비게이션 내부 고객 을 방출하고있어
this.customerService.saveNewCustomer(customer) 
    .subscribe(res => { 
     this.customer = res; 
     this.customerService.sharedCustomer = this.customer; 
     this.router.navigateByUrl('/earning/customers/profile'); 
    }); 
    } 

공지 사항, 고객이 서비스에 저장된 제대로뿐만 아니라 F를 멀리 이동하지됩니다 것을 보장하기 위해 그 전에 롬 페이지. 귀하의 세부 정보 페이지에서 다음

:

ngOnInit() { 
    this.customer = this.customerService.sharedCustomer; 
} 
+0

나는 'ngOnInit() { this.customerService.customer $ .subscribe 내 프로필 페이지에 정의되지 않은 받고있는 것으로 보인다 (고객 => { this.customer = 고객, }); console.log (this.customer); } 고객 개체 유형 인 API에서 데이터가 다시 전송됩니다. –

+0

내 서비스 클래스를 포함하도록 내 질문이 업데이트되었습니다. –

+0

구독 정보에 고객이 실제로 가입했는지, 아직 정의되지 않았는지 확인 했습니까?:) – Alex

관련 문제