首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Injectable服务中的HTTP提供程序

@Injectable服务中的HTTP提供程序
EN

Stack Overflow用户
提问于 2015-12-30 10:05:40
回答 1查看 353关注 0票数 2

Angular2现在正处于测试阶段,我的公司决定在这方面做一些工作。我试图从我的服务中提出一个请求。我浏览了所有的网络,但都没有用。(也许帖子是在Beta发布之前写的)。

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

代码语言:javascript
复制
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]);

我的BrandsComponent注射我的BrandsService。在这里,我的服务代码:

代码语言:javascript
复制
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 [];
	}
}

在我的控制台中,我已经创建了'Task service‘日志,但是任何ajax请求都在进行。

我不能告诉你我尝试过什么,因为我改变了我的代码大约10亿次。

谢谢你的帮助!

@编辑:

这里是我的BrandsComponent代码:

代码语言:javascript
复制
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;
	}
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-30 10:42:49

事实上,可观察的人是懒惰的。这意味着在使用subscribe方法在其上附加一些响应侦听器之前不会发送相应的HTTP请求。

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

代码语言:javascript
复制
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();
  }
  (...)
}

希望它能帮到你,蒂埃里

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34527275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档