Search code examples
jsonangularangular2-servicesangular-observable

What is dispose of null in Angular 4


I am getting "what is dispose of null" when load the page. I am to get list of data but unable to show those record in view. Here i added code snippet to understand my requirement

Angular JS Service File

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class PostsService {
 data: any = null;
 totalDocs: number;
 url: any = 'http://localhost:3000/services/';
 constructor(private _http: Http) { }

 public getPosts() {
  return this._http.get(this.url + 'posts')
              .map((res: Response) => res.json());
 }    
}

//End Angular JS Web service*

Node JS code to get data from MongoDB

import { default as Category} from "../models/Category";
import { default as Post} from "../models/Post";
import { Request, Response, NextFunction } from "express";


export let getPostsAPI = (req: Request, res: Response, next: NextFunction) => {
const post: any = req.body;
const cond: any = {};
if (!this.empty(post.kword)) {

 *//$text is full text index*

  cond.$text = {$search : post.kword};
}
if (!this.empty(post.location)) {
  cond.city = {$regex: new RegExp("^" + post.location, "i") };
}

*Counting total number of records and 
Here Post is reference of collection, its working fine and generating data as i given bottom of this post.*
Post.count(cond).then(totalDocs => {
  Post.find(cond).sort({created_at: -1}).then(result => {
    const results = {data: result, totalDocs: totalDocs};
    console.log(results);
    res.end("" + JSON.stringify(results));
  });
 });  
};

End node JS Code

Angular JS home.component.ts where i am calling web serive to render data in angular view

export class HomeComponent implements OnInit {
  results: any = {};
  model: any = {};
  constructor(private posts: PostsService) {
    posts.getPosts().subscribe(res => {
    console.log(res.totalDocs); // Showing number of records in console.
    this.results = res.data; // this is throwing error. 
  *//Error is: TypeError: Cannot read property 'dispose' of null*
  });
 this.model.kword = '';
 this.model.location = '';
}
  ngOnInit() {
  }
}

Template Code

<div class="container">
  <app-filter [result]=value (clicked)="searchJob($event)"></app-filter>
  <!-- /.row -->
  <div class="row" >
    <div class="col-sm-10 my-10" *ngFor="let post of results | async">
      <div class="card">
          <div class="card-body">
              <h3 class="mt-1"><a [routerLink]="['/job', post.company, post.title, post._id]">{{ post.title }}</a></h3>
              <p class="mt-1" *ngIf="post.company"><span class="badge badge-primary">{{post.company}}</span></p>
              <p class="mt-1" *ngIf="post.salary_min">Salary up to: &#8377;{{post.salary_min}} - &#8377;{{post.salary_max}}</p>
              <p class="mt-1" *ngIf="post.city || post.state">Location: {{post.city}}, <span *ngIf="post.state">{{post.state}}</span></p>
              <p class="mt-1" *ngIf="post.description">{{post.description | slice:0:150}}[...]</p>
          </div>
      </div>
    </div>
  </div>
  <!-- /.row -->
</div>

End Template JSON DATA WHICH COMING FROM API
{ "data": [ { "title":"test title", "description":"test description" } ], "totalRecords":2 }

i attached a screenshot of error.

error which is showing in console


Solution

  • The async pipe subscribes to an observable for you, so it needs to be fed an observable, you're feeding it the resulting value of an observable, which is why you're seeing this error.

    Do it like this instead:

    results: Observable<any>;
    model: any = {};
    constructor(private posts: PostsService) {
      this.results = posts.getPosts().map(res => res.data);
      this.model.kword = '';
      this.model.location = '';
    }
    

    Now you're setting the "results" value to the actual observable, and letting async handle the subscription part.