簡體   English   中英

Angular 9 http 響應后的類型轉換問題

[英]Angular 9 typecast issue after http response

我有一個組件,它在初始化時從 api 檢索學生信息。 這是我的cmponent-version1上的onIniti代碼

ngOnInit(): void {
    if(!this.student) {
      this.studentsService.getStudentDetail(this.id).subscribe(
        (response: Student) => {
          this.student = response;
        },
        error => console.log(error)
      )
    }
  }

這是我的學生服務版本1中的function

getStudentDetail(id: number): Observable<Student> {
    return this.httpClient.get<Student>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions);
  }

一切正常。 現在,僅出於教學目的(我是 javascript/typescript 的新手),我想重構我的服務,以便使用單個get function 在不帶參數的情況下返回學生列表,而是返回學生詳細信息使用特定 ID 調用時的信息。 這是學生服務版本2

getStudents(id?: number): Observable<Student[]> {
    if(id)
      return this.httpClient.get<Student[]>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions);
    else
      return this.httpClient.get<Student[]>(this.studentsUrl, this.baseService.httpOptions);
  }

鑒於我的 function 的簽名聲明它返回一個可觀察的學生數組,在我的組件中,我需要一種從Student[]Student的類型轉換。 我就是這樣做的: component-version2

ngOnInit(): void {
    if(!this.student) {
      this.studentsService.getStudents(this.id).subscribe(
        (response: Student[]) => {
          this.student = response[0] as Student;
        },
        error => console.log(error)
      )
    }
  }

這不起作用,因此在 init 之后, student var 仍然未定義。 我不明白為什么,對我來說一切似乎都是正確的(盡管這種重構不是一個好主意。同樣,我只是想了解背后的錯誤)我也嘗試this.student = response.pop() as Student; 同樣的結果,不工作。

ngOnInit(): void {
if(!this.student) {
  this.studentsService.getStudents(this.id).subscribe(
    (response: Student[]) => {
      // Hope, this.student will have type as any, public student: any
      this.student = !this.id ? response[0] as Student : response as Student[];
    },
    error => console.log(error)
  )
}

}

始終,嘗試返回一個數組以避免沖突。 在上面的代碼中,三元運算符將完成您的工作。 因為,如果您有一個 id,這意味着您正在詢問特定的學生信息,否則您正在詢問所有學生記錄。

您的服務現在應該對您大喊大叫,因為您在對編譯器撒謊……您的返回類型不是Observable<Student[]>它的Observable<Student[] | Student> Observable<Student[] | Student> ...我不同意一個 function 的負責人,無論是單身還是名單,但你可以強迫它成為單一情況下的名單......

return this.httpClient.get<Student>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions).pipe(
  map(student => [student])
);

如果它不是數組,則沒有類型轉換會將其轉換為數組。 如果您願意,您需要明確地將其設為數組。

重載方法的簽名,如下所示:

class StudentService {
  get(id: number) | Observable<Student>;
  get(): Observable<Student[]>;
  get(id: number | undefined): Observable<Student[]> | Observable<Student> {
    if(id !== undefined)
      return this.httpClient.get<Student[]>(`${this.studentsUrl}${id}/`, this.baseService.httpOptions);
    else
      return this.httpClient.get<Student>(this.studentsUrl, this.baseService.httpOptions);
  }
} 

請注意如何重命名該方法以使其在任何一種情況下都有意義,返回類型如何與id參數的存在相關,以及如何修改檢查以適應0作為有效 id 的可能性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM