0

我尝试了很多格式,感觉就快到了。我不知道这个获取请求有什么问题。

我一直在通过 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)

引号.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
}
4

1 回答 1

0

要注入服务,您需要将其添加到构造函数参数中,就像使用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)
    );
  }
}
于 2022-03-05T11:52:00.433 回答