Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度2将表单数据传递给另一个组件_Javascript_Angular - Fatal编程技术网

Javascript 角度2将表单数据传递给另一个组件

Javascript 角度2将表单数据传递给另一个组件,javascript,angular,Javascript,Angular,我有一个表单,允许用户创建一个帐户,一旦用户点击提交按钮,用户将被导航到另一个页面,其中包含他们创建的帐户的详细信息。我遇到的问题是将该对象传递给details视图 例如,这里是我的表单组件 import {Component, OnInit, OnDestroy, Input} from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import {Customer}

我有一个表单,允许用户创建一个帐户,一旦用户点击提交按钮,用户将被导航到另一个页面,其中包含他们创建的帐户的详细信息。我遇到的问题是将该对象传递给details视图

例如,这里是我的表单组件

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:['']
    });
  }
从'@angular/core'导入{Component,OnInit,OnDestroy,Input};
从'@angular/forms'导入{FormGroup,FormBuilder,Validators};
从“./model/Customer”导入{Customer};
从'@angular/Router'导入{Router};
从“./service/customer.service”导入{CustomerService};
从“./customer profile/customer profile.component”导入{CustomerProfileComponent};
@组成部分({
选择器:“应用程序新客户”,
templateUrl:“./new customer.component.html”,
样式URL:['./new customer.component.css']
})
导出类NewCustomerComponent实现OnInit{
@输入()客户:客户;
//这是唯一的开发数据,请勿在prod中使用
私人国家=[];
私人客户资源=[];
私有二次资源=[];
//创建论坛组
public-newCustomerForm:FormGroup;
public submitted:boolean;//跟踪表单是否已提交
构造函数(私有fb:FormBuilder、公共customerService:customerService、私有路由器:路由器){
这是一个国家=[
{value:'UK'},
{值:'Germany'},
{值:'Turkey'},
{值:'Italy'}
];
此。customerSources=[
{value:'通过朋友或同事(而不是客户)},
{value:'通过现有客户端'},
{value:'直接销售(如冷电话、直接邮件、电子邮件)},
{value:'网络搜索,例如Google'}
];
this.secondarySources=[
{值:'第一次雇用'},
{value:'具有长业务名称的测试客户端'},
{value:'Abbigail West'}
];
}
恩戈尼尼特(){
this.newCustomerForm=this.fb.group({
id:[''],
公司名称:['',[Validators.required,Validators.minLength(5)],
增值税:[''],
地址:[''],
国家:[''],
名字:[''],
姓氏:[''],
电话:[''],
电子邮件:[''[Validators.required,Validators.minLength(5)],
客户来源:[''],
次要来源:['']
});
}
这是我的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>

一旦你添加了新客户,你可以回来让他们查看他们的发票和付款-如果你启用了Paypal,他们也可以通过Paypal付款

新客户详细信息 需要客户名称(至少5个字符)。 {{country.value} 您的主要联系人 需要电子邮件(至少5个字符)。 客源 {{cs.value}} {{ss.value}} 取消 拯救
客户服务在我的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');
    }
  }


} 
saveNewCustomer(客户:客户,isValid:boolean){
如果(有效){
this.submited=true;//将表单提交设置为true
this.customerService.saveNewCustomer(客户)
.订阅(
res=>this.customer,
error=>console.log(错误)
);
this.router.navigateByUrl('/earning/customers/profile');
}
}
} 
这是我希望customer对象使用的组件,以便它出现在视图中

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>
从'@angular/core'导入{Component,OnInit,Input};
从“./model/Customer”导入{Customer};
从“./newcustomer/newcustomer.component”导入{NewCustomerComponent};
@组成部分({
选择器:“应用程序客户配置文件”,
templateUrl:“./customer profile.component.html”,
样式URL:['./customer profile.component.css'],
提供者:[新CustomerComponent]
})
导出类CustomerProfileComponent实现OnInit{
@输入()客户:客户;
构造函数(){
console.log(this.customer);
}
恩戈尼尼特(){
}
}
客户资料

{{客户}}

但是customer在CustomerProfile组件中未定义。我不确定我做错了什么。如果有人能给我指出正确的方向,我将不胜感激

根据建议更新以包括服务类别

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


}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response,Headers,RequestOptions};
从“angular2 cookie/services/cookies.service”导入{CookieService};
从“rxjs”导入{可观察,主题};
导入'rxjs/add/operator/map';
导入“rxjs/add/operator/catch”;
从“./model/Customer”导入{Customer};
@可注射()
导出类CustomerService{
私有csrfToken;
private newCustomerUrl=“/earning/customers/new”;
私人客户=新主题();
customer$=this.customer.asObservable();
构造函数(公共http:http,私有cookieService:cookieService){
这个.getCsrfToken();
}
getCsrfToken(){
this.csrfToken=this.cookieService.get(“PLAY_SESSION”).substring(this.cookieService.get(“PLAY_SESSION”).indexOf(“csrfToken”);
}
saveNewCustomer(客户:客户):可观察{
让标题=新标题({
“内容类型”:“应用程序/json”
});
let options=newrequestoptions({headers:headers});
使用post reque返回this.http.post(this.newCustomerUrl+“?”+this.csrfToken,customer,options)/…文件
public sharedCustomer = {};
  this.customerService.saveNewCustomer(customer)
    .subscribe(res => {
       this.customer = res;
       this.customerService.sharedCustomer = this.customer;
       this.router.navigateByUrl('/earning/customers/profile');
    });
  }
ngOnInit() {
  this.customer = this.customerService.sharedCustomer;
}