【发布时间】:2017-05-05 05:39:56
【问题描述】:
我正在运行《英雄之旅》应用程序,但我想扩展它以进行 ajax 调用。
我有一个提供数据的 WebAPI 服务(启用了 CORS),并使用 JQuery $.post 和 $GetJson 用一个愚蠢的非 Angular 客户端证明了它......一切进展顺利......
这是我的 hero-details.component.ts 文件 (很高兴包括任何其他可能有帮助的...)
import {Component , Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { HttpModule } from '@angular/http';
import 'rxjs/add/operator/switchMap';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls : ['./hero-detail.component.css']
})
export class HeroDetailComponent { // implements OnInit {
@Input() hero: Hero;
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
submitted = false;
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location,
$http //**--LINE OF INTEREST #2**
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
}
save(): void {
this.heroService.update(this.hero)
.then(() => this.goBack());
}
goBack(): void {
this.location.back();
}
onSubmit() { this.submitted = true; }
callService( ) {
var uri = 'http://localhost:61212/api/heros';
//**// LINE OF INTEREST #1**
$http({
method: 'GET',
url: uri
}).then(function () { alert('success'); }, function () { alert('fail');});
};
}
如果我尝试编译,我会得到 p>
TS2304: Cannot find '$http'
我可以注释 $HTTP 调用(Line of Interest #1),它编译、运行,然后我进入函数并命中断点,在该断点处声明并分配变量“uri”。所以我有理由确定我已经隔离了问题。
所以我相信,基于几个小时的谷歌搜索,我需要将 $http 对象 DI 到这个组件中
但是当我将 $http 传递给构造函数时(LINE OF INTEREST #2),当我尝试编译时出现以下错误
TS7006 Parameter '$http' implicitly has an 'any' type
我在 Google 上搜索了很多,Larry 和 Sergy 要求我取消它。 我发现 $http 被传递到控制器中,也许我错过了一些东西,但我似乎无法将这些文章翻译成适用于此的东西。
1) 注入 $http 对象是需要做的事情,我说得对吗
2) 语法是什么?
【问题讨论】:
-
您正在使用哪个版本的 angular 2?为什么
$http而不仅仅是private http: Http? -
@angular/common@~4.0.0 我对你的问题的回答仅仅是因为我正在尝试使用谷歌作为学习工具,它很棒,但有时会让你陷入困境......我拉出的所有页面似乎都将 $http 传递给了构造函数。让我试试把 $
-
原来我使用的示例是 Angular 1 代码。直到我尝试了其他一些事情,我才意识到这一点。
标签: javascript angularjs xmlhttprequest