尝试使用Angular的http.get【超级初学者】
我想写下一份有关在Angular中进行异步通信的方法备忘录,以尽可能简明易懂地为对TypeScript和Angular不太熟悉的人做准备。
使用的版本
kuniatsu$ ng -v
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@angular/cli: 1.1.3
node: 7.5.0
os: darwin x64
@angular/animations: 4.3.2
@angular/common: 4.3.2
@angular/compiler: 4.3.2
@angular/core: 4.3.2
@angular/forms: 4.3.2
@angular/http: 4.3.2
@angular/platform-browser: 4.3.2
@angular/platform-browser-dynamic: 4.3.2
@angular/router: 4.3.2
@angular/cli: 1.1.3
@angular/compiler-cli: 4.3.2
@angular/language-service: 4.3.2
kuniatsu$ npm -v
4.1.2
文件夹结构
文件几乎都被省略了。
.
├── README.md
├── e2e
├── node_modules
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.component.spec.ts
│ │ └── app.module.ts
│ ├── assets
│ └── environments
├── .angular-cli.json
└── package.json
app.module.ts 的中文解释是什么?
首先,在app.module.ts中添加HttpModule。HttpModule是一个用于添加HTTP客户端功能的模块。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {HttpModule} from "@angular/http";//ここを追加
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule//ここを追加
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts 组件
接下来在app.component.ts文件中实现获取功能。
为了方便不了解TypeScript的人阅读,我特意写得很长。
我尽量以类似Java的方式来编写。
import { Component } from '@angular/core';
import {Http, Response} from "@angular/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private http:Http;
//非同期通信先のURLを指定する。
URL = 'assets/test.json';
//「コンストラクター」クラスが実体化された時に走る
constructor(http:Http){
this.http = http;
}
getMethod(){
//http.getをするためのオブジェクトを生成
var httpObj = this.http.get(this.URL);
//成功時・失敗時の動作を指定する。
httpObj.subscribe(this.getSuccess,this.getError);
}
//http.getが成功した時に走るメソッド
getSuccess(response:Response){
console.log(response.text());
}
//http.getが失敗した時に走るメソッド
getError(error){
console.log(error);
}
}
应用组件HTML
在html中编写点击事件,以使通过app.component.ts创建的getMethod()方法运行。
<button (click)="getMethod()">Get!</button>
测试.json
因为目前没有要阅读的文件,所以需要根据app.component.ts的URL指定创建test.json文件。
{
"name":"test.json",
"level":"easy"
}
将创建的test.json文件放入assets文件夹中。
.
├── README.md
├── e2e
├── node_modules
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.component.spec.ts
│ │ └── app.module.ts
│ ├── assets
│ │ └── test.json
│ └── environments
├── .angular-cli.json
└── package.json
执行
用这个命令“ng serve”来执行应用程序。

没有问题,可以看到已经提取出了创建的JSON的内容。
构造函数的编写方式改变
因为app.component.ts的写法不太像TypeScript,所以我会将其改成常见的写法。
首先,如果要将构造函数的参数赋值给成员变量,可以仅省略构造函数的参数。
export class AppComponent {
private http:Http;
constructor(http:Http){
this.http = http;
}
}
可以这样进行修改。
export class AppComponent {
constructor(private http:Http){}
}
匿名函数
下面我们来尝试使用ES6中引入的Lambda表达式。
getSuccess(response:Response){
console.log(response.text());
}
这个可以用以下的方式来改写。
getSuccess = response=>{
console.log(response.text());
}
省略变量
另外,由于可以直接写变量的内容,所以
getMethod(){
var httpObj = this.http.get(this.URL);
httpObj.subscribe(this.getSuccess,this.getError);
}
//http.getが成功した時に走るメソッド
getSuccess = response=>{
console.log(response.text());
}
}
这个可以根据以下的方式进行改写。
getMethod(){
var httpObj = this.http.get(this.URL);
httpObj.subscribe(response=>{
console.log(response.text());
},
this.getError
);
}
如果将这个错误传达给错误方
getMethod(){
var httpObj = this.http.get(this.URL);
httpObj.subscribe(response=>{
console.log(response.text());
},error=>{
console.log(error);
});
}
这一句话的表达如下。
最后,无需再将httpObj重新分配给变量。
getMethod(){
this.http.get(this.URL)
.subscribe(response=>{
console.log(response.text());
},error=>{
console.log(error);
});
}
可以用下面这种方式来写。
完成状态
根据上述情况来写,
import { Component } from '@angular/core';
import {Http, Response} from "@angular/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
//非同期通信先のURLを指定する。
URL = 'assets/test.json';
//コンストラクタークラスが実体化された時に走る
constructor(private http:Http){}
getMethod(){
this.http.get(this.URL)
.subscribe(response=>{
//成功時の処理
console.log(response.text());
},error=>{
//失敗時の処理
console.log(error);
});
}
我可以看出,你写得非常清楚。