PallMallShow
PallMallShow

Reputation: 137

HTTP PROVIDERS in @Injectable Service

Angular2, now in beta, my company decide to work on it a little bit. I tried to set a request from my service. I browse all the internet, but nothing working. (Maybe posts was written before Beta release).

So, I have my boot.ts like this :

import {bootstrap} from 'angular2/platform/browser';
import {Component, provide} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';

import {BrandsComponent} from './brands/brands.component';
import {BrandsService} from './brands/brands.service';

@Component({
	selector: 'my-app',
	template: `
		<brands></brands>
	`,
	directives: [BrandsComponent]
})

export class AppComponent {
}


bootstrap(AppComponent, [HTTP_PROVIDERS, BrandsService]);

My BrandsComponent inject my BrandsService. Here my service code :

import {Http} from 'angular2/http';
import {Injectable, Inject} from 'angular2/core';

@Injectable()
export class BrandsService{
	constructor(public http: Http) {
		console.log('Task Service created.', http);
		http.get('http://google.fr');
	}

	getBrands(){
		//return this.http.get('./brands.json');
		return [];
	}
}

In my console, I have the 'Task service created' log, but any ajax request is going.

I can't tell you what I've tried, cause I change my code about a billion times.

Thank for your help !

@Edit :

Here my BrandsComponent code :

import {Component} from 'angular2/core';

import {Brand} from './brand.interface';
import {BrandsService} from './brands.service';

import {ModelsComponent} from './../models/models.component';

@Component({
	selector: 'brands',
	templateUrl: 'templates/brands/list.html',
	providers: [BrandsService],
	directives: [ModelsComponent]
})

export class BrandsComponent implements OnInit{
	public brands;
	public selectedBrand : Brand;

	constructor(private _brandsService: BrandsService) { }

	/*
	* Get all brands from brands service
	*/
	getBrands(){
		this.brands = this._brandsService.getBrands();
	}

	/*
	* On component init, get all brands from service
	*/
	ngOnInit(){
		this.getBrands();
	}

	/*
	* Called when li of brand list was clicked
	*/
	onSelect(brand : Brand){
		this.selectedBrand = brand;
	}
}

Upvotes: 2

Views: 358

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202246

In fact observables are lazy. This means that corresponding HTTP requests aren't sent before attaching some response listeners on them using the subscribe method.

Adding a subscribe method in the constructor of your BrandsService should trigger your HTTP request:

import {Http} from 'angular2/http';
import {Injectable, Inject} from 'angular2/core';

@Injectable()
export class BrandsService{
  constructor(public http: Http) {
    console.log('Task Service created.', http);
    http.get('http://google.fr').subscribe();
  }
  (...)
}

Hope it helps you, Thierry

Upvotes: 1

Related Questions