angular - 在 Angular 应用程序中使用 graphql-codegen 时出现错误 "Object is of type unknown"

标签 angular typescript graphql graphql-codegen

我有这个 Angular 应用程序,它使用 graphql-codegen 通过 graphql 端点为应用程序生成模型。

该组件在容器内包含一个图像标签:

<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>

编译器对 (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>' 

后者说:

Object is of type 'unknown'

该组件的 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)
  }


}

如上面代码所示,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
        }
      }
    }
        `;

我在这个应用程序中使用的包如下:

    "@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",

如何消除这些错误?

谢谢!

最佳答案

Blogposts 类型和代码中稍后的重新影响之间存在明显的类型检查不一致。

使用

$any((blogPosts | async)...

避免类型检查错误而不纠正类型不一致。

至于 $any 的易读性,这里是 doc 中的内容。 :

Use the $any() type-cast function in certain contexts to opt out of type-checking for a part of the expression

关于angular - 在 Angular 应用程序中使用 graphql-codegen 时出现错误 "Object is of type unknown",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72878468/

相关文章:

angular - Native Storage Error,不显示如下画面

typescript - Angular2 - 订阅服务变量变化

javascript - 从 Promise 返回数据到 GraphQL

javascript - 如何重新获取直到从服务器返回特定值? ( react Apollo )

graphql - 在默认配置中使用 Helm 会阻止 graphql playground 打开

angular - 在 mat-form-field 控件之前设置图像图标

data-binding - 使用 ngModel 的 Angular 2 双向绑定(bind)不起作用

Angular 10 - CommonJS 或 AMD 依赖可能导致优化救助

typescript - 如何按序号访问 Typescript 枚举

javascript - Angular 没有输入时如何将值设置为0