0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Angular:HttpClientのサンプル(同期版、非同期版)

Posted at

前書き

  • 自分の勉強メモ、ご参考まで

AngularのHttpClient(AJAX)のサンプル(非同期版)

app.module.tsHttpClientModuleをimport。

app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  ......
  imports: [
    HttpClientModule
  ]
  bootstrap: [AppComponent]
  ......
})

HttpClientを利用する

home.component.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';

constructor(private http: HttpClient) { }

onSearch () {
  let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'  }) };

  console.log('1) ajax start...');
  this.http.get('http://localhost/Mock/receiptMap.json', httpOptions)
    .subscribe(response => {
      console.log(response);
      console.log('2) ajax over...');
    });    
  console.log('3) search over...');
}

// 結果は以下である
1) ajax start...
3) search over...
2) ajax over...

AngularのHttpClient(AJAX)のサンプル(同期版)

HttpClientを利用する

home.component.ts
import { lastValueFrom } from 'rxjs';

async onSearch () {
  let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };

  console.log('1) ajax start...');
  const f = await lastValueFrom(this.http.get('http://localhost/AiReceiptApiMock/receiptMap.json', httpOptions));
  console.log(f);
  console.log('2) ajax over...');
  console.log('3) search over...');
}

// 結果は以下である
1) ajax start...
2) ajax over...
3) search over...
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?