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]);
我的BrandsComponent注射我的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 [];
}
}
在我的控制台中,我已经创建了'Task service‘日志,但是任何ajax请求都在进行。
我不能告诉你我尝试过什么,因为我改变了我的代码大约10亿次。
谢谢你的帮助!
@编辑:
这里是我的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;
}
}
发布于 2015-12-30 10:42:49
事实上,可观察的人是懒惰的。这意味着在使用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();
}
(...)
}希望它能帮到你,蒂埃里
https://stackoverflow.com/questions/34527275
复制相似问题