Angular 7两个组件之间的数据共享

时间:2019-01-30 17:01:04

标签: angular

当从creditcardcomponent向存储值的config.service向功能getAddress()请求时,我没有获得预期的Address对象值。我得到的是初始值,而不是更新的值。这是config.service

import { Injectable, Optional } from '@angular/core';
 import { Address }from '../_models/address';
 import { config } from 'rxjs';

 export class AddressServiceConfig {
   addressConfig = 
   new Address(
     {
       name:"",
       address_city: "",
       address_line1: "",
       address_line2: "",
       address_state: "",
       address_zip: "",
       address_country: ""
     }
   )
   constructor(@Optional() config: ConfigService) {
      this.addressConfig = config._addressConfig; 
   }
 }

@Injectable()
export class ConfigService {

  public _addressConfig = 
  new Address(
    {
      name:"",
      address_city: "",
      address_line1: "",
      address_line2: "",
      address_state: "",
      address_zip: "",
      address_country: ""
    }
  )

  constructor(@Optional() config: AddressServiceConfig) {
    if (config) { this._addressConfig = config.addressConfig; }
  }

  // set the address from stripe component
    setAddress(value) {
        this._addressConfig = value;
        console.log('set address is ', this._addressConfig);

    }

     getAddress():Address {
      // get the address to the creditcard component  
      console.log('get address is ', this._addressConfig);
        return this._addressConfig;
    }  

}

这是creditcardComponent:

import { Component, OnInit, ViewChild, Input } from '@angular/core'
import { StripeScriptTag, StripeToken } from "stripe-angular"
import { environment } from '../environments/environment'
import { NgForm } from '@angular/forms'
import { Observable } from 'rxjs'

import { Address } from '../_models/address'
import { CreditCardService } from '../_services/creditcard.service'
import { ConfigService } from '../_services/config.service'


declare var Stripe;
@Component({
  selector: 'app-creditcard',
  templateUrl: './creditcard.component.html',
  styleUrls: ['./creditcard.component.css']
})
export class CreditCardComponent implements OnInit {

  public ccAddress: Address;
  extraData$: Observable<Address>;

  token:StripeToken;
  error:Error;

  Stripe: any; 
  @ViewChild("yourForm")
   yourForm: NgForm;
  private publishableKey:string = `${environment.stripeKey}`;

  constructor(private creditCardService: CreditCardService,
      public stripeScriptTag: StripeScriptTag,
      public configService: ConfigService) {
        this.stripeScriptTag.setPublishableKey( this.publishableKey );
  }

   ngOnInit(){

      this.getAddress(); 
      console.log("From configService", this.ccAddress); 
   }

   getAddress(): void {
    this.ccAddress = this.configService.getAddress();
      console.log('this.ccAddress is ', this.ccAddress);
   }

这是我在控制台窗口中从config.service console.log获得的响应:

get address is  Address {name: "", address_city: "", address_line1: "", 
address_line2: "", address_state: "", …}

我在条纹组件中调用setAddress()。这是条带组件代码:

import { Component, ViewChild, OnInit } from '@angular/core'
import { NgForm } from '@angular/forms'

import { Address } from '../_models/address'
import { Observable } from 'rxjs';
import { ConfigService } from '../_services/config.service';

declare var Stripe;
@Component({
  selector: 'app-stripe',
  templateUrl: './stripe.component.html',
  styleUrls: ['./stripe.component.css'] 
})
export class StripeComponent implements OnInit {

  // totally right to make address instance of Address class
  public address = 
    new Address(
      {
        name:"",
        address_city: "",
        address_line1: "",
        address_line2: "",
        address_state: "",
        address_zip: "",
        address_country: ""
      }
    )

  // create observable
  address$ = new Observable((observer) => {
    // observable execution
     observer.next(this.address )
     observer.complete()
    })  

  Stripe: any; 
  @ViewChild("yourForm")
  yourForm: NgForm;

  constructor(private configService: ConfigService) { }

  ngOnInit(){
    // create observable address$
    //which will log the address when the observable gets a value.
      this.address$.subscribe( (address: Address) => { 
console.log(address); }) ;
  }

  onSubmitAddress(){
      this.address$.subscribe( (address: Address) => { 
        this.address = address;
        console.log('here is the onSubmit address', this.address); }) 
        this.configService.setAddress(this.address);  <-- setAddress()
  }

}

这是app.module.ts代码:

imports: [
CoreModule.forRoot({
  addressConfig: new Address({
    name: "",
    address_city: "",
    address_line1: "",
    address_line2: "",
    address_state: "",
    address_zip: "",
    address_country: ""
  }),
}),
],

1 个答案:

答案 0 :(得分:1)

看起来getAddress仅在ngOnInit中被调用?如果是这样,它将不知道何时更改值。

   ngOnInit(){

      this.getAddress(); 
      console.log("From configService", this.ccAddress); 
   }

   getAddress(): void {
    this.ccAddress = this.configService.getAddress();
      console.log('this.ccAddress is ', this.ccAddress);
   }

尝试将简单的ccAddress属性更改为吸气剂。然后,它将在每次更改时重新获取它。

get ccAddress(): Address {
  return this.configService.getAddress();
}