【问题标题】:Angular typescript response model and type error角度打字稿响应模型和类型错误
【发布时间】:2021-11-16 17:54:57
【问题描述】:

在使用 NodeJS 服务器的本地 MEAN 堆栈应用程序上,我的端点响应返回数组 os Post:

{
  "message": "Posts fetched successfully!",
  "posts": [
    {
     "_id": "618b22ff9e50776ed377c4eb",
     "title": "aaaaaaaaaaaaaa",
     "body": "xxxxxxxxxxxxx",
     "__v": 0
    },
  ]
}

带有响应模型的 Angular 服务:

export interface PostResponse {
  message: string;
  posts: Post;
}

  getPosts(): Observable<PostResponse> {
   return this.http.get<PostResponse>(this.postsUrl + '/api/posts');
  }

PostComponent 注入上面的 Postservice:

    export interface Post {
      id: number;
      title: string;
      body: string;
    }


export class PostsComponent implements OnInit {
  posts: Post[] = [];
  constructor(private postService: PostService) {}    

    ngOnInit() {
      this.postService
       .getPosts()
       .pipe(
         map((data) => {
             console.log('data : ', data.posts._id);  // vide #1
          return {
           id: data.posts.id,                       // _id error <HERE>
           title: data.posts.title,
           content: data.posts.body,
         };
       })
      ).subscribe((response) => {
       this.posts = response;                          // error <HERE>
       console.log('posts updated : ', this.posts);
    });

}

问题。

Q-1:在我的组件上,当我映射响应数据时,所需的道具是 data.posts.id,而不是 data.posts._id,但流数据是: #1 { "_id": "618b22ff9e50776ed377c4eb", “标题”:“啊啊啊啊啊啊”, “正文”:“xxxxxxxxxxxxx”, “__v”:0 },

如果我使用 _id,我会收到错误“帖子”类型上不存在属性“_id”

这是因为我的 PostResponse 接口吗?

_id 来自我的 mongo 数据库,我假设我必须强制转换响应数据以匹配我不使用 _ID 而是使用 ID 的前端结构。

Q-2:在订阅时,在 this.posts = response 我收到错误:

输入 '{ id: number;标题:字符串;内容:字符串; }' 缺少类型 'Post[]' 的以下属性:length、pop、push、concat 和 26 more.ts(2740)

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    Q1:是的,这是因为您在 getPosts() 中使用的 PostResponse 接口。该接口中的 Posts 属性指的是 Post 接口,这意味着帖子对象中的所有属性都来自 Post 接口。修复它:

    export interface Post {
      _id: string;
      title: string;
      body: string;
    

    }

    Q2:您正在映射来自 PostResponse 的 json 响应而不是“发布”属性值,因此它将返回对象而不是数组。试试这个:

     this.postService
       .getPosts()
       .pipe(
         map((data) => {
          return data.posts.map(v => {
           _id: v._id,                       
           title: v.title,
           content: v.body,
          })
       })
      ).subscribe((response) => {
       this.posts = response;  
    });
    

    并将 post 属性类型设置为 PostResponse 中的数组:

    export interface PostResponse {
      message: string;
      posts: Post[];
     }
    

    【讨论】:

      【解决方案2】:

      据我了解,您的界面是错误的。

      export interface PostResponse {
        message: string;
        posts: Post[];
      }
      
      export interface Post {
        _id: string;
        title: string;
        body: string;
      }
      

      那些似乎是正确的接口。

      要获取数据,您应该:

      this.postService
             .getPosts()
             .subscribe((response) => {
               this.posts = response?.posts; 
         });
      

      或者

      this.postService
                 .getPosts()
                 .subscribe((response) => {
                   this.posts = response?.posts?.map(res => {
                     return {
                       _id: res.id,
                       title: res.title,
                       body: res.body,
                     }
                   }); 
             });
      

      【讨论】:

        【解决方案3】:

        您需要将接口POST 中的id 更改为_id,因为这就是mongodb 将发送给您的内容。 更新后的界面应该是这样的:

        export interface POST{
          _id: string,
          title: string,
          body: string,  
        }
        

        PostResponse 应该是:

        export default PostResponse{
          message: string;
          posts: Post[];
        }
        

        以这种方式映射数据:

        this.postService
                   .getPosts()
                   .subscribe((response) => {
                     this.posts = response?.posts?.map(data => {
                       return {
                         _id: data.id,
                         title: data.title,
                         body: data.body,
                       }
                     }); 
               });
        

        【讨论】:

          猜你喜欢
          • 2021-06-10
          • 1970-01-01
          • 1970-01-01
          • 2018-12-17
          • 2021-08-01
          • 1970-01-01
          • 2017-10-30
          • 2021-06-06
          • 2018-11-23
          相关资源
          最近更新 更多