Angular 7 Singleton Service在两个组件之间进行通信

时间:2019-01-29 21:00:00

标签: angular typescript dependency-injection angular7

我有两个组成部分和一项服务。我想使用该服务存储一个通用值。 StripeComponent设置服务中的值。我收到以下错误:

  

无法读取未定义的属性'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'],
  providers: [ConfigService]
})
export class StripeComponent implements OnInit {
  public address = 
    new Address(
  {
    name:"",
    address_city: "",
    address_line1: "",
    address_line2: "",
    address_state: "",
    address_zip: "",
    address_country: ""
  }
)
configService: ConfigService 

  constructor() {         
   }

  ngOnInit(){
  // create observable address$
    this.address$.subscribe( (address: Address) => { 
    console.log(address); }) ;

      this.configService.setAddress(this.address); <-- error here

  } 

}

这是我的服务

import { Injectable } from '@angular/core'
import { Address }from '../_models/address';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {

  constructor() { }

  private config : Address;
  // set the address from stripe component
    setAddress(value) {
      this.config = value;
    }

  public getAddress() {
          return this.config;
  }

}

2 个答案:

答案 0 :(得分:3)

您需要将ConfigService注入到StripeComponent的构造函数中,例如

export class StripeComponent implements OnInit {
    constructor(private configService: ConfigService) {}
}

How to use create and consume services in Angular

答案 1 :(得分:1)

当您将 ConfigService 声明为“可注入”(public static String encrypt(String str) { String pw = "pass"; byte[] pwb=pw.getBytes(),msb=str.getBytes(),xor_result; xor_result=new byte[msb.length]; int j=0; while(j<pwb.length){ xor_result[j]=(byte)(0xff &(pwb[j]^msb[j]));//you see in this code at least 8 bits are xored in one instruction depending on the processor(or am i wrong!?) j++; } return getBinaryString(new String( xor_result)); } )时,必须将其注入到构造函数中:

@Injectable