1
這是我的應用程序的一個組件,它可以很好地工作,但它會使this.stylistDetails = data;
這一行出現錯誤。可有人建議解決這個問題Angular http客戶端錯誤
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-search-results',
templateUrl: './search-results.component.html',
styleUrls: ['./search-results.component.css']
})
export class SearchResultsComponent implements OnInit {
stylistDetails: Stylist[] = [];
need;
type;
showMessage;
preferred_locations = [];
countResults;
// onNotifyClicked(message:string): void{
// this.showMessage = message;
// }
onClickLocFiltered(): void{
this.http.get('/api/stylist/getStylist/loc').subscribe(
data => {
this.stylistDetails = data;
this.countResults = this.stylistDetails.length;
}
);
}
constructor(private route: ActivatedRoute, private http: HttpClient) {
this.http.get<Stylist>('/api/stylist/getStylistName').subscribe(
data => {
this.stylistDetails = data;
// console.log(this.stylistName);
// console.log(this.stylistName.length);
this.countResults = this.stylistDetails.length;
}
);
}
ngOnInit() {
this.route
.queryParams
.subscribe(params => {
// Defaults to 0 if no query param provided.
this.need = params['need'] || 0;
this.type = params['type'] || 0;
});
}
}
interface Stylist {
name: string;
address: string;
cost: number;
skills: string[];
}
的方式而這正是我的終端顯示
ERROR in src/app/search-results/search-results.component.ts(27,9): error TS2322: Type 'Object' is not assignabl
e to type 'Stylist[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
src/app/search-results/search-results.component.ts(27,9): error TS2322: Type 'Object' is not assignable to type
'Stylist[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Property 'includes' is missing in type 'Object'.
src/app/search-results/search-results.component.ts(37,9): error TS2322: Type 'Stylist' is not assignable to typ
e 'Stylist[]'.
src/app/search-results/search-results.component.ts(37,9): error TS2322: Type 'Stylist' is not assignable to typ
e 'Stylist[]'.
Property 'includes' is missing in type 'Stylist'.
你舒爾stylistDetails和數據有相同的類型? –
是的都是相同的類型 –
您的類型需要匹配,當您將數據分配給'Stylist []'時,您正在使用'Stylist'。其次,你並不是說你期待的是哪種類型的響應,而當Angular返回一個對象時,你試圖賦予'Stylist []'。告訴Angular你期待的數據類型'Stylist []':'this.http.get('/ api/stylist/getStylist/loc')'https://angular.io/guide/http#typechecking-the-響應 –
Alex