Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

801
Views
Modelo de respuesta de mecanografiado angular y error de tipo

En una aplicación de pila MEAN local que usa el servidor NodeJS, mi respuesta de punto final devuelve la publicación del sistema operativo:

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

Servicio angular con un modelo de respuesta:

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

PostComponent inyecta el Postservice anterior:

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

}

Pregunta.

P-1: En mi Componente, cuando asigno datos de respuesta, la propiedad requerida es data.posts.id, en lugar de data.posts._id, pero los datos de transmisión son: #1 { "_id": "618b22ff9e50776ed377c4eb", "title ": "aaaaaaaaaaaaaaa", "cuerpo": "xxxxxxxxxxxxx", "__v": 0 },

si uso _id, aparece un error La propiedad '_id' no existe en el tipo 'Publicar'

¿Esto se debe a mi interfaz PostResponse?

_id proviene de mi base de datos mongo, supuse que tenía que forzar la transformación de los datos de respuesta para que coincidieran con la estructura de front-end donde no uso _ID sino ID.

P-2: en la suscripción, en this.posts = respuesta Recibo un error:

Escriba '{ id: número; título: cadena; contenido: cadena; }' faltan las siguientes propiedades del tipo 'Post[]': length, pop, push, concat y 26 más.ts(2740)

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

P1: Sí, eso se debe a su interfaz PostResponse que usa en getPosts(). Los atributos de las publicaciones en esa interfaz se refieren a la interfaz de publicación, lo que significa que todos los atributos en los objetos de publicación provienen de la interfaz de publicación. arreglarlo con:

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

}

P2: está asignando la respuesta json de PostResponse y no el valor del atributo 'post', por lo que devolverá un objeto en lugar de una matriz. prueba esto:

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

Y haga que el tipo de atributo de publicación sea una matriz en PostResponse:

 export interface PostResponse { message: string; posts: Post[]; }
over 4 years ago · Santiago Trujillo Report

0

Por lo que tengo entendido, sus interfaces están mal.

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

Esas parecen ser las interfaces correctas.

Para obtener los datos debes:

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

O

 this.postService .getPosts() .subscribe((response) => { this.posts = response?.posts?.map(res => { return { _id: res.id, title: res.title, body: res.body, } }); });
over 4 years ago · Santiago Trujillo Report

0

Debe cambiar la id en la interfaz POST a _id porque eso es lo que mongodb le enviará. La interfaz actualizada debería ser así:

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

Y PostResponse debería ser:

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

Asigne los datos de esta manera:

 this.postService .getPosts() .subscribe((response) => { this.posts = response?.posts?.map(data => { return { _id: data.id, title: data.title, body: data.body, } }); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!