【问题标题】:Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]Typescript:Type X 缺少 Type Y 长度、pop、push、concat 等 26 个属性中的以下属性。 [2740]
【发布时间】:2019-06-25 19:37:42
【问题描述】:

我有这个产品界面:

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[]':长度、pop、push、concat 等 26 种。 [2740]

删除productsArray 变量上的输入会消除错误,但不明白为什么这不起作用,因为服务器响应是Products 类型的对象数组?

【问题讨论】:

  • getProducts() 被定义为为单个 Observable 返回一个 Product,但您将观察到的结果分配给一个 Product[] 数组。
  • 小修正。将类型改为数组return this.http.get&lt;Product[]&gt;(api/products/v1/);

标签: angular typescript typescript-typings


【解决方案1】:

您必须指定响应的类型:

this.productService.getProducts().subscribe(res => {
    this.productsArray = res;
});

试试这个:

this.productService.getProducts().subscribe((res: Product[]) => {
    this.productsArray = res;
});

【讨论】:

    【解决方案2】:

    对我来说,错误是由错误的 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)
      }
    }
    

    【讨论】:

      【解决方案3】:

      我在 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"}],
            },
          });
      

      有时像这样的简单错误可能会导致问题。希望这会对某人有所帮助。

      【讨论】:

        【解决方案4】:

        这个错误也可能是因为你没有订阅 Observable。

        示例,而不是:

        this.products = this.productService.getProducts();
        

        这样做:

           this.productService.getProducts().subscribe({
            next: products=>this.products = products,
            error: err=>this.errorMessage = err
           });
        

        【讨论】:

          【解决方案5】:

          我有同样的问题,我解决了如下 定义一个像我这样的接口

          export class Notification {
              id: number;
              heading: string;
              link: string;
          }
          

          并在nofificationService中写入

          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);
          }
          

          【讨论】:

            【解决方案6】:

            对于像我这样的新手,不要为服务响应分配变量,意思是这样做

            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();
                }
            }
            

            【讨论】:

              【解决方案7】:

              您正在返回 Observable&lt;Product&gt; 并期望它在 subscribe 回调中是 Product[]

              http.get()getProducts() 返回的类型应该是Observable&lt;Product[]&gt;

              public getProducts(): Observable<Product[]> {
                  return this.http.get<Product[]>(`api/products/v1/`);
              }
              

              【讨论】:

              • 注意:这需要“import { Observable } from 'rxjs';”在服务类中
              【解决方案8】:

              您忘记将 getProducts 返回类型标记为数组。在您的 getProducts 中,它说它将返回一个产品。所以改成这样:

              public getProducts(): Observable<Product[]> {
                  return this.http.get<Product[]>(`api/products/v1/`);
                }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-02-04
                • 1970-01-01
                • 1970-01-01
                • 2019-12-28
                • 2022-01-24
                • 2016-11-22
                • 2023-03-07
                • 2019-09-11
                相关资源
                最近更新 更多