Link to home
Start Free TrialLog in
Avatar of chalie001
chalie001

asked on

error in post app

hi am having error in angular
User generated image
import {Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import {HttpClient} from '@angular/common/http';

import {Post} from './post.model';

@Injectable({providedIn: 'root'})
export class PostsService{
    private posts: Post[] = [];
    private postsUpdated = new Subject<Post[]>();

    constructor(private http: HttpClient){}

    getPosts(){
        this.http.get<{message: string,posts: Post }>('http://localhost:3000/api/posts')
          .subscribe((postData) =>{
        this.posts[] = postData.posts;
        this.postsUpdated.next(...this.posts);
    });
    }

    getPostUpdateListener(){
        return this.postsUpdated.asObservable();
    }

    addPost(title: string, content: string){
        const post: Post = {id:null,title: title,content: content};
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);

    }
}

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

this.posts[] = postData.posts;

Open in new window

Should be
this.posts = postData.posts;

Open in new window

Avatar of chalie001
chalie001

ASKER

its giving this error
User generated image
See my last post

Look at the error window at the bottom of the screen grab
User generated image
Please try using
     getPosts(){
        this.http.get<{message: string,posts: Post[] }>('http://localhost:3000/api/posts')
          .subscribe((postData) =>{
        this.posts = postData.posts;
        this.postsUpdated.next(...this.posts);
    });

Open in new window

@Julian Hansen,
I made two changes to getPosts method. I agree that my second change is the change that you posted in your first post above here.
But, the first  change was to the following line.
this.http.get<{message: string,posts: Post }>('http://localhost:3000/api/posts')

Open in new window

 I changed it to
this.http.get<{message: string,posts: Post[] }>('http://localhost:3000/api/posts')

Open in new window


The shape of the response is an object with a property  posts  which is an array of Posts.
Please look at
https://stackblitz.com/edit/angular-k4nexg   
If you remove the [] that I have added to that line, then you see error that is exactly what is reported by  chalie001
That won't cause an error nor will it affect the result - the type hinting is there to ensure you don't make a mistake in your coding (given the leniency of JavaScript around types).

I agree it should be corrected but in the context of this problem it won't fix the error the user is happening.
@Julian Hansen,
Are you saying that the one change that you posted is enough to get the IDE to stop showing errors?

I  added  more of chalie001's code to my stackBlitz.  I needed three changes to make the IDE happy.
       getPosts(){
        this.http.get<{posts: Post[] }>('http://localhost:3000/api/posts')
          .subscribe((postData) =>{
        this.posts = postData.posts;
        this.postsUpdated.next([...this.posts]); //third change
    });
}

Open in new window

Are you saying that the one change that you posted is enough to get the IDE to stop showing errors?
For that piece of code yes

This is syntactically wrong in JavaScript

x[] = someValue;

Open in new window

It throws an error
The following is just a hint to Typescript that on what you are expecting back so that it can validate what you do in the callback
this.http.get<SomeType>(url).toPromise().then(result => doSomethingWith(result);

Open in new window

You are telling TypeScript you expect the http call to return data of SomeType
If you tell it SomeType and you are actually returning SomeOtherType - TypeScript won't pick that up - unless you specify the type in the callback
this.http.get<SomeType>(url).toPromise().then((result:SomeOtherType) => doSomethingWith(result);

Open in new window

The console will show an error but the code will still run.

In your case you have this
.subscribe((postData) =>{

Open in new window

No type specified on the callback parameter - so what you hint in the get is irrelevant.
If you want to be 100% correct then do this
getPosts(){
        this.http.get<{message: string,posts: Post[] }>('http://localhost:3000/api/posts')
          .subscribe((postData: Post[]) =>{
        this.posts = postData.posts;
        this.postsUpdated.next(...this.posts);
    });

Open in new window


Now you are telling the compiler you are expecting an array of Posts back and you are declaring your callback as such.
@Julian Hansen,  thank you for taking time to explain.
I guess my mistake was assuming that the the red wiggly lines are always bad and need to be eliminated.
I guess my mistake was assuming that the the red wiggly lines are always bad and need to be eliminated.

They should - don't misunderstand me - the red underlines are signs something is not right. But there is a difference between those that are going to result in the code breaking and those that are related to type hinting.

In this case we need to eliminate the ones that are causing the code not to compile - so as not to create confusion.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.