타이프스크립트:유형 X에는 유형 Y 길이, 팝, 푸시, 콘캣 등의 속성이 없습니다.[2740]
제품 인터페이스는 다음과 같습니다.
export interface Product{
code: string;
description: string;
type: string;
}
메서드 호출 제품 끝점이 있는 서비스:
public getProducts(): Observable<Product> {
return this.http.get<Product>(`api/products/v1/`);
}
그리고 이 서비스를 사용하여 제품을 입수하는 컴포넌트입니다.
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
}
}
이 상태에서는 에러가 발생합니다.
[ts] 유형 'Product[]'에서 길이, 팝, 푸시, 콘캣 등의 속성이 누락되었습니다.[2740]
에 대한 입력 제거productsArray
variable은 오류를 제거하지만 서버 응답은 다음과 같은 유형의 개체 배열이기 때문에 이 오류가 작동하지 않는 이유를 알 수 없습니다.Products
?
돌아오시는군요Observable<Product>
기대하면서Product[]
안에서.subscribe
콜백
반환된 유형http.get()
그리고.getProducts()
그래야 한다Observable<Product[]>
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
getProducts 반환 유형을 배열로 표시하지 않았습니다.getProducts에는 단일 제품을 반환한다고 기재되어 있습니다.따라서 다음과 같이 변경합니다.
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
저 같은 신입사원에게는 서비스 응답에 변수를 할당하지 마십시오. 즉,
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
}
}
대신
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productsArray = this.productService.getProducts().subscribe();
}
}
응답 유형을 지정해야 합니다.
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
이것을 시험해 보세요.
this.productService.getProducts().subscribe((res: Product[]) => {
this.productsArray = res;
});
나도 같은 문제가 있었고, 나와 같은 인터페이스를 정의하기 위해 다음과 같이 해결했다.
export class Notification {
id: number;
heading: string;
link: string;
}
및 nofification Service 쓰기
allNotifications: Notification[];
//NotificationDetail: Notification;
private notificationsUrl = 'assets/data/notification.json'; // URL to web api
private downloadsUrl = 'assets/data/download.json'; // URL to web api
constructor(private httpClient: HttpClient ) { }
getNotifications(): Observable<Notification[]> {
//return this.allNotifications = this.NotificationDetail.slice(0);
return this.httpClient.get<Notification[]>
(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
}
컴포넌트 쓰기
constructor(private notificationService: NotificationService) {
}
ngOnInit() {
/* get Notifications */
this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}
GraphQL 변환 입력 객체에 동일한 오류 메시지가 표시되었고 문제를 발견했습니다. 실제로 변환의 경우 입력으로 객체 배열을 예상하지만 입력으로 단일 객체를 삽입하려고 합니다.예를 들어 다음과 같습니다.
첫 번째 시도
const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
mutation: MUTATION,
variables: {
objects: {id: 1, name: "John Doe"},
},
});
어레이로서의 변환 콜 수정
const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
mutation: MUTATION,
variables: {
objects: [{id: 1, name: "John Doe"}],
},
});
때때로 이와 같은 단순한 실수가 문제를 일으킬 수 있습니다.이게 누군가에게 도움이 되길 바라.
이 오류는 관찰 가능에 가입하지 않은 경우에도 발생할 수 있습니다.
예:
this.products = this.productService.getProducts();
다음을 수행합니다.
this.productService.getProducts().subscribe({
next: products=>this.products = products,
error: err=>this.errorMessage = err
});
저는 URL 문자열의 잘못된 유형의 힌트로 인해 오류가 발생했습니다.사용:
export class TodoService {
apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
내가 사용했어야 할 곳에
export class TodoService {
apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
언급URL : https://stackoverflow.com/questions/54475893/typescript-type-x-is-missing-the-following-properties-from-type-y-length-pop
'programing' 카테고리의 다른 글
WooCommerce에서 모든 제품 카테고리 가져오기 (0) | 2023.03.06 |
---|---|
Angular에서의 비싱글톤 서비스JS (0) | 2023.03.06 |
JSON Hijacking은 최신 브라우저에서 여전히 문제가 됩니까? (0) | 2023.03.01 |
상태를 어떻게 기다리죠? (0) | 2023.03.01 |
JSON을 기존 개체로 역직렬화(Java) (0) | 2023.03.01 |