2
votes

I don't know but, Some weird thing happening up, I referred the default code provided on "Angular.io" to perform angular service calls, but some how ngOninit method is not getting called. I have also implemented component from OnInit. and added @Injectable to user.services.ts. But still don't know where I am getting wrong.
Below is the code for the reference.

app.component.ts

//app.components.ts

import { Component } from '@angular/core';
import {User} from './user';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
 title = 'Society CRM';
}

user.ts

export class User
{
  _id : string;
  name: string;
  email: string;
  username: string;
  password: string;
  phone: string;
  address: string;
  role: string;
  created_date: string; 
}

user-list.component.ts

import {Component,OnInit} from '@angular/core';
import {User} from './user';
import {UserService} from './user.service';
import { Headers, RequestOptions } from '@angular/http';
@Component({
 selector:'user-list',
 templateUrl:'./user-list.html',
 providers: [ UserService ]
})

export class UserListComponent implements OnInit{
errorMessage: string;
users: User[];
mode = 'Observable';
constructor (private userService: UserService) {};
ngOnInit() { 
 this.getUsersList();
 alert('here');         
}
getUsersList() {  
  return this.userService.getUsersList()
                 .subscribe(
                   users => this.users = users,
                   error =>  this.errorMessage = <any>error);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { UserListComponent }  from './user-list.component';
import { UserService } from './user.service';
import { FormsModule }   from '@angular/forms'; // <-- NgModel lives here

@NgModule({
declarations: [
  AppComponent,
  UserListComponent
],
imports: [
  BrowserModule,
  HttpModule,
  FormsModule
 ],
 providers: [UserService],
 bootstrap: [AppComponent]
})
export class AppModule { }

user.service.ts

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import {User} from './user';
import { Headers, RequestOptions } from '@angular/http';
@Injectable()
export class UserService
{
        constructor (private http:Http){}
        private api_url = "http://localhost:3000/api/";
        getUsersList() : Observable<User[]>
        {
            let headers = new Headers();
            headers.append('Access-Control-Allow-Origin', '*');
            headers.append('Access-Control-Allow-Credentials', 'true');
            headers.append('Access-Control-Allow-Methods', 'GET');
            headers.append('Access-Control-Allow-Headers', 'Content-Type');
            let options = new RequestOptions({headers: headers});
            return this.http.get(this.api_url+'getUsersList',options)
                .map(this.extractData)
                .catch(this.handleError);

        }

        private extractData(res: Response) {
            let body = res.json();
            return body.data || {};
        }
        private handleError(error: Response | any) {
            // In a real world app, you might use a remote logging infrastructure
            let errMsg: string;
            if (error instanceof Response) {
                const body = error.json() || '';
                const err = body.error || JSON.stringify(body);
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Observable.throw(errMsg);
        }
}  

I don't know what exactly is happening with the above code, no error being shown on firebug console or browser console. Any help would be thankful

2
Any errors in the console? - hagner
Console not showing any errors - Swapnil Deo
How do you know that the ngOnInit method isn't called? Have you add your user -ist.component inside app.component.html? - porgo
Post app.component.html - Vega
<h1> {{title}} </h1> - Swapnil Deo

2 Answers

2
votes

Check that you indeed use the component... For example is the tag <user-list></user-list> defined somewhere in your html?

2
votes

Change your app.component.html code by adding this:

<user-list></user-list>

OnInit isn't called because you don't use user-list.component.