简体   繁体   English

在 Angular 应用程序中使用 graphql-codegen 时出现错误“对象类型未知”

[英]Error "Object is of type unknown" when using graphql-codegen in the Angular application

I have this Angular application which enjoys graphql-codegen to generate model for the application through graphql end point.我有这个 Angular 应用程序,它喜欢 graphql-codegen 通过 graphql 端点为应用程序生成模型。

the component includes an image tag inside a container:该组件在容器内包含一个图像标签:

<ng-container *ngFor="let blog of (blogPosts | async)?.blogPost  | paginate: config">
    <img class="image" *ngIf="blog.image.urls" src="http://localhost:5002{{blog.image.urls}}"
                        alt="Placeholder image">
</ng-container>

The compiler complains on both (blogPosts | async)?.blogPost and image part of the blog the former says:编译器抱怨(blogPosts | async)?.blogPost和博客的图像部分,前者说:

Argument of type '({ __typename?: "BlogPost" | undefined; path: string; subtitle?: string | null | undefined; displayText?: string | null | undefined; owner: string; publishedUtc?: any; markdownBody?: { ...; } | ... 1 more ... | undefined; image?: { ...; } | ... 1 more ... | undefined; } | null)[] | null | undefined' is not assignable to parameter of type 'Collection<unknown>' 

And the latter says:后者说:

Object is of type 'unknown'

The typescript part of the component includes a graphql query which is in the generated code by the graphql-codegen library:该组件的 typescript 部分包括一个 graphql 查询,该查询位于 graphql-codegen 库生成的代码中:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map, take} from 'rxjs/operators';
import { BlogPostsQuery, BlogPostsGQL } from '../graphql/graphql';


@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {
  public responsive: boolean = true;
  blogPosts!: Observable<BlogPostsQuery>;
  modalIsActive!: boolean;
  values!: string;
  
  
  public config = {
    itemsPerPage: 1,
    // tslint:disable-next-line: radix
    currentPage: parseInt(sessionStorage.getItem('blogPage') || '') || 0
  };

  constructor(
    private router: Router,
    private allBlogPostGQL: BlogPostsGQL
  ) {

  }

  ngOnInit() {

    this.blogPosts =  this.allBlogPostGQL
    .watch()
    .valueChanges
    .pipe(
      map(blogs =>  blogs.data
      ));

  }


  onPageChange(number: number) {
    sessionStorage.setItem('blogPage', JSON.stringify(number));
    this.config.currentPage = number;
    console.log('eeeee', number);

  }

  showMore(name: string) {
    this.router.navigate(['/blog', name]);
    console.log('aaaaaaaa', this.config.currentPage)
  }


}

As shown in the code above BlogPostsGQL is the source of data in the blog component and its code is as below:如上代码所示,BlogPostsGQL 是博客组件中的数据来源,其代码如下:

import { gql } from 'apollo-angular';
import { Injectable } from '@angular/core';
import * as Apollo from 'apollo-angular';
export type Maybe<T> = T | null;
export type InputMaybe<T> = Maybe<T>;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };

export type BlogPostsQuery = { __typename?: 'Query', blogPost?: Array<{ __typename?: 'BlogPost', path: string, subtitle?: string | null, displayText?: string | null, owner: string, publishedUtc?: any | null, markdownBody?: { __typename?: 'MarkdownBodyPart', markdown?: string | null } | null, image?: { __typename?: 'MediaField', urls?: Array<string | null> | null } | null } | null> | null };

export type BlogPostsQueryVariables = Exact<{ [key: string]: never; }>;

    @Injectable({
        providedIn: 'root'
      })
      export class BlogPostsGQL extends Apollo.Query<BlogPostsQuery, BlogPostsQueryVariables> {
        document = BlogPostsDocument;
        
        constructor(apollo: Apollo.Apollo) {
          super(apollo);
        }
      }
    export const CurrentBlogDocument = gql`
        query currentBlog($urlPath: String) {
      blogPost(where: {path: $urlPath}) {
        path
        subtitle
        displayText
        owner
        publishedUtc
        image {
          urls
        }
        markdownBody {
          markdown
        }
      }
    }
        `;

The packages I use in this application are as below:我在这个应用程序中使用的包如下:

    "@apollo/client": "^3.0.0",
    "@graphql-codegen/cli": "^2.7.0",
    "@graphql-codegen/introspection": "^2.1.1",
    "@graphql-codegen/typescript": "^2.6.0",
    "@graphql-codegen/typescript-apollo-angular": "^3.4.13",
    "@graphql-codegen/typescript-operations": "^2.4.3",
    "apollo-angular": "^3.0.1",
    "graphql": "^16.5.0",

How can I get rid of these errors?我怎样才能摆脱这些错误?

Thanks!谢谢!

There is obvious type checking incoherence between the Blogposts type and re-affectation later in the code. Blogposts 类型和代码后面的重新影响之间存在明显的类型检查不一致。

use利用

$any((blogPosts | async)...

to avoid type-checking error without correcting the type incoherence.在不纠正类型不连贯的情况下避免类型检查错误。

As for the legibility of $any, here is what is in the doc :至于 $any 的易读性,这是文档中的内容:

Use the $any() type-cast function in certain contexts to opt out of type-checking for a part of the expression在某些上下文中使用 $any() 类型转换函数来选择不对表达式的一部分进行类型检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在客户端解析器中导入类型时,如何避免使用 Apollo 客户端和 `graphql-codegen` 的角度项目中的循环依赖? - How to avoid circular dependency in angular project with Apollo client and `graphql-codegen` when importing types in client resolver? 带有插值的 graphql-codegen 动态字段 - graphql-codegen dynamic fields with interpolation Angular Apollo:错误:GraphQL 错误:“Mutation”类型的“AuthLogin”字段上的未知参数“用户名” - Angular Apollo: Error: GraphQL error: Unknown argument “username” on field “AuthLogin” of type “Mutation” 使用Angular 8 HttpClient和Python Flask时发生未知错误 - Unknown Error when using Angular 8 HttpClient and Python Flask 量角器 - 未知错误:使用by.model时未定义角度 - Protractor - unknown error: angular is not defined when using by.model 当我使用解析器和Apollo graphQL实现时,Angular应用程序冻结 - Angular application freeze when I'm using resolver and apollo graphQL implementation 400 (Bad Request) - 在 angular2 中将内容类型更改为 application/graphql - 400 (Bad Request) - Change the content type to application/graphql in angular2 ngUpgrade中的未知提供程序错误(Angular 1/2混合应用程序) - Unknown provider error in ngUpgrade (Angular 1/2 hybrid application) Angular 在访问表单控件的错误对象上的未知属性时不会抛出错误 - Angular does not throw an error when accessing an unknown property on a form control's error object 错误 TS2571:Object 的类型为“未知” - error TS2571: Object is of type 'unknown'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM