Angular 13:我的HTTP Get Request出了什么问题



我已经尝试了很多格式,感觉我几乎做到了。我不知道这个get请求出了什么问题。

我一直在通过Pluralsight学习教程,并完全遵循了他们正在做的事情。不管怎样都没有运气。

请提供一些帮助。非常感谢!!

以下是控制台错误:

ERROR TypeError: Cannot read properties of undefined (reading 'getProductId')
at StepperComponent.ngOnInit (stepper.component.ts:33:24)
at callHook (core.mjs:2542:1)
at callHooks (core.mjs:2511:1)
at executeInitAndCheckHooks (core.mjs:2462:1)
at refreshView (core.mjs:9499:1)
at refreshComponent (core.mjs:10655:1)
at refreshChildComponents (core.mjs:9280:1)
at refreshView (core.mjs:9534:1)
at renderComponentOrTemplate (core.mjs:9598:1)
at tickRootContext (core.mjs:10829:1)

quotes.service.ts文件:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Products } from '../models/products';
@Injectable({
providedIn: 'root',
})
export class QuotesService {
constructor(private http: HttpClient) {}
// GET Destination Countries:
private destinationUrl = <my-url>
// GET Request - subscribe in component.ts
getProductId(): Observable<Products[]> {
return this.http.get<Products[]>(this.destinationUrl, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'bearer <my-token>'
}),
});
}
}

stepper.component.ts文件

export class StepperComponent implements OnInit {

//declare quotesService
quotesService: any;
constructor(private _formBuilder: FormBuilder) {}
ngOnInit() {
this.quotesService.getProductId().subscribe(
(data: Products[]) => (this.quotesService = data),
(err: any) => console.log(err)
);
}
onSubmit() {
console.log('Submit Works');
}
}

products.ts文件:

export interface Products {
product_id: number,
age: number,
currency_id: string,
destination_country_ids: string,
host_country_id: string,
country_state: string, // if host country = US (optional)
start_date: Date,
end_date: Date,
trip_cost: number,
deposit_date: Date,
winter_sports_extension: boolean
}

要注入服务,需要将其添加到构造函数参数中,就像使用FormBuilder服务一样。请参阅文档。

更新的stepper.component.ts文件:

export class StepperComponent implements OnInit {
constructor(private _formBuilder: FormBuilder,
private quotesService: QuotesService) {}
ngOnInit() {
this.quotesService.getProductId().subscribe(
(data: Products[]) => (this.quotesService = data),
(err: any) => console.log(err)
);
}
}

相关内容

最新更新