0

I want to get some data from nodejs to angular and list it on a web page.

I tried to do it but i get no answer (the web page is blank, no errors)

this is the post.model:

export interface Post {
    id: string;
    token: string;
    lat: String;
    lng: String;
}

The JSON I'm working on (from database):

{
    "location": [
        {
            "_id": "5f3429f9fe89ef3658c5ec17",
            "lat": "44.4363255",
            "lng": "25.9912393",
            "token": "edb153fb9d8d5628",
            "__v": 0
        },
        {
            "_id": "5f342fbadae3a42884852505",
            "lat": "44.4363228",
            "lng": "25.9912314",
            "token": "c30af1934c22f4eb",
            "__v": 0
        }
    ]
}

post-list.component:

export class PostListComponent implements OnInit, OnDestroy {
    posts: Post[] = [];
    private postsSub: Subscription;

    constructor(public postsService: PostsService) {
        //dependency-injection
    }
    ngOnInit() {
        this.postsService.getPosts();
        this.postsSub = this.postsService
            .getPostUpdateListener()
            .subscribe((posts: Post[]) => {
                this.posts = posts;
            });
    }

    onShow() {
        console.log('TODO');
    }

    ngOnDestroy() {
        this.postsSub.unsubscribe();
    }

post-list.component.html:

<mat-accordion multi="true" *ngIf="posts.length > 0">
    <mat-expansion-panel *ngFor="let post of posts">
        <mat-expansion-panel-header>
            {{ post.token }}
        </mat-expansion-panel-header>
        <p>{{ post.lat }}</p>
        <p>{{ post.lng }}</p>
        <mat-action-row>
            <button mat-raised-button color="accent" (click)="onShow(post.id)">
                SHOW
            </button>
        </mat-action-row>
    </mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf="posts.length <= 0">No posts added yet</p>

and also the post.service:

export class PostsService {
    private posts: Post[] = [];
    private postsUpdated = new Subject<Post[]>();

    constructor(private http: HttpClient) {}

    getPosts() {
        this.http
            .get<{ posts: any[] }>('127.0.0.1:8000/location')
            .pipe(
                map((postData) => {
                    return postData.posts.map((post) => {
                        return {
                            id: post._id,
                            token: post.token,
                            lat: post.lat,
                            lng: post.lng,
                        };
                    });
                })
            )
            .subscribe((transformedPosts) => {
                this.posts = transformedPosts;
                this.postsUpdated.next([...this.posts]);
            });
    }

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

Basically I'm retrieving some data from a android app and save it on a mongodb database using nodejs. The next step of my project is to list the data from the database on a web page.

I tried to get the data via getPosts() method (see post.service), then list it. As I told you, nothing shows on the web page.

the app.component.html is simple, I just called an to show a map (I will show some coords on a map later) and the , which should show the data from the database.

If i delete the <app-post-list></app-post-list>, the webpage displays a google map, so the rest of the code is working, but when i add <app-post-list></app-post-list>, it doesn't show anything anymore. Any ideas, please?

---Edit

I resolved the "nothing appearing issue". Now, the data can't be displayed: No posts added yet

this is the developer console log:

5
  • Does it do the call? Commented Aug 12, 2020 at 18:38
  • What do you mean and how can i verify this? Commented Aug 12, 2020 at 18:41
  • I think you should probably debug the post update listener. If that listener doesn't work then you will not able to get the post records. My opinion is that you should return the array of values from get method itself with proper JSON. Commented Aug 12, 2020 at 18:42
  • Check your network tab in the browser console.. Commented Aug 12, 2020 at 18:42
  • As I can see, i'm getting an error on the browser console: ``` core.js:4197 ERROR NullInjectorError: R3InjectorError(AppModule)[PostsService -> HttpClient -> HttpClient -> HttpClient]: ``` Commented Aug 12, 2020 at 18:47

1 Answer 1

1

From your last comment, i think you just forgot to import HttpClientModule in your AppModule.

Make sure to add schema "http://" to your target url, like this:

        .get<{ posts: any[] }>('http://127.0.0.1:8000/location')

If you don't do so, Angular will just interpret it as http://localhost:4200/127.0.0.1/location

Sign up to request clarification or add additional context in comments.

12 Comments

You really saved me a lot of time. Yes, this was an issue. Now I can see again the map. Also, "No posts added yet" appears, that's the case the client can't fetch data from nodejs (or at least it doesn't save the data), but I can't get why..
Can you check your developer console output and update your post with it please ? try to console.log(this.posts) right after you assign it in your subscription code.
this is what i get:
``` core.js:4197 ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "localhost:4200/127.0.0.1:8000/location", ok: false, …} ```
that means the client doesn't get the data correct from server maybe?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.