Angular 7 Singleton Service 在两个组件之间进行通信 [英] Angular 7 Singleton Service To Communicate between two components
本文介绍了Angular 7 Singleton Service 在两个组件之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个组件和一个服务.我想使用该服务来存储一个公共值.StripeComponent
设置服务中的值.我收到以下错误:
I have two components and a service. I want to use the service to store a common value. StripeComponent
sets the value in the service. I get the following error:
无法读取未定义的属性setAddress"
Cannot read property 'setAddress' of undefined
这是我的组件:
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;
}
}
推荐答案
你需要将 ConfigService
注入到 StripeComponent
的构造函数中,例如
You need to inject ConfigService
to the constructor of StripeComponent
e.g
export class StripeComponent implements OnInit {
constructor(private configService: ConfigService) {}
}
这篇关于Angular 7 Singleton Service 在两个组件之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文