我收到此错误:ERROR TypeError: Cannot read property 'subscribeNewsletter' of undefined at NewsletterComponent.subscribeNewsletter (newsletter.component.ts:47)
尝试创建服务以从表单订阅新闻通讯时出现。
这是我的NewsletterComponent
:
import { Component, OnInit, Inject, forwardRef } from '@angular/core';
import { NewsletterService } from '../common/service/newsletter.service';
import { NewsletterDto } from '../common/model/dto/newsletter-dto';
import { FormGroup } from "@angular/forms";
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-user-cmp',
templateUrl: 'newsletter.component.html'
})
export class NewsletterComponent implements OnInit {
newsletterService: NewsletterService;
newsletterForm: FormGroup;
newsletter: NewsletterDto;
ngOnInit() {
this.newsletterForm = new FormGroup({
'subscribe': new FormControl(null),
});
}
constructor() {}
subscribeNewsletter(): void {
this.newsletter = {
subscribe: this.newsletterForm.controls['subscribe'].value
};
this.newsletterService.subscribeNewsletter(this.newsletter).subscribe(newsletter => this.newsletter = newsletter);
}
}
这是我的
NewsletterService
:import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { NewsletterDto } from '../model/dto/newsletter-dto';
import { Observable, of } from 'rxjs';
import { map, catchError } from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class NewsletterService {
private newsletterUrl = 'rest/newsletter/subscription';
constructor(private http: Http) { }
subscribeNewsletter(newsletter: NewsletterDto): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http
.post(this.newsletterUrl, newsletter, options).pipe(
map((res: any) => res.json()),
catchError(<T>(error: any, result?: T) => {
console.log(error);
return of(result as T);
})
);
}
}
我真的不明白问题出在哪里吗?谁能给我一些启发?谢谢 !
最佳答案
您应该在constructor
中注入服务
constructor(public newsletterService: NewsletterService) {
/* do the construction stuff */
}
确保删除在构造函数之前定义的其他
newsletterService
属性。