错误的“对象是类型未知”。当在角度应用中使用GraphQl-codegen

发布于 2025-02-13 17:47:57 字数 4343 浏览 0 评论 0原文

我有这个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)

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'

该 组件包括一个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)
  }


}

的如下:

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

如何摆脱这些错误?

谢谢!

I have this Angular application which enjoys graphql-codegen to generate model for the application through graphql end point.

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:

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:

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:

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱人如己 2025-02-20 17:47:57

Blogposts类型与后期重新影响之间存在明显的类型检查不一致。

用于

$any((blogPosts | async)...

避免在不纠正类型不一致的情况下进行类型检查错误。

至于$ ANY的可读性,以下是

在某些情况下使用$ ANY()类型式函数以选择退出
对表达式的一部分进行类型检查

There is obvious type checking incoherence between the Blogposts type and re-affectation later in the code.

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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文