javascript - @Injectable 服务中的 HTTP 提供程序

标签 javascript http service angular provider

Angular2,现在处于测试阶段,我的公司决定对其进行一些研究。 我试图从我的服务中设置一个请求。我浏览了所有互联网,但没有任何效果。 (也许帖子是在 Beta 发布之前写的)。

所以,我的 boot.ts 是这样的:

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)我的 BrandsService。 这是我的服务代码:

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 [];
	}
}

在我的控制台中,我有“任务服务已创建”日志,但任何 ajax 请求都在进行中。

我无法告诉您我尝试了什么,因为我更改了我的代码大约十亿次。

感谢您的帮助!

@编辑:

这是我的 BrandsComponent 代码:

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;
	}
}

最佳答案

事实上,observables 是惰性的。这意味着在使用 subscribe 方法附加一些响应监听器之前,不会发送相应的 HTTP 请求。

BrandsService 的构造函数中添加订阅方法应该会触发您的 HTTP 请求:

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();
  }
  (...)
}

希望对你有帮助, 蒂埃里

关于javascript - @Injectable 服务中的 HTTP 提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527275/

相关文章:

javascript - Window.print() 函数弄乱了表格

javascript - 如何在 AS3 中制作类似 Gridster.js 的 Tile/Grid 布局?

javascript - express .js : Headers already sent on REST API

ios - HTTPURLResponse allHeaderFields Swift 3 大写

linux - systemd - 如何从系统服务访问当前用户名?

android - 无法从 Android 服务中的 sharedPreference 接收更新值

php - 使用 php 在其他站点上运行 javascript

javascript - Function.prototype.method 中的 return this 有什么作用?

Python -- 连接错误 : Max retries exceeded

android - 启动后台定位服务不工作