4
2

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 3 years have passed since last update.

【Angular】ExpressとAngularの連携

Posted at

APIくんと仲良くなりたいッ…

expressとAngularの開発環境構築の流れを簡単にまとめました。
親フォルダの下にserverフォルダとangularのweb-appフォルダを作成していきます。

server

mkdir server
cd server
npm init
npm install express
npm install -D @types/express

保存したときに素早く確認したいのでts-node-devを導入します。
変更を保存したらリロードするだけで反映されるようになります。

npm install typescript
npm install -D ts-node-dev

package.jsonのscriptsにdevを追加します。

  "scripts": {
    "dev": "ts-node-dev --respawn src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

tsconfig.jsonを作ります

tsc --init

index.tsを作っていきます
tsc: command not foundと言われたら
npm i -g typescriptを実行してもう一度。

mkdir src
touch src/index.ts

src/index.ts

import Express from "express";

const app = Express();
const port = 3000;

app.get('/',(req,res)=>{
    res.send('こんにちは');
});

app.listen(port,()=>{
    console.log(`Express app listening at http://localhost:${port}/`)
});

実行

npm run dev

スクリーンショット 2021-03-14 14.13.47.png
localhost:3000にアクセスするとちゃんと表示されました。

Angularプロジェクトと連携させていきます
親フォルダ直下で

 ng new web-app
 cd web-app
 touch proxy.conf.json

proxy.conf.json

{
    "/api":{
        "target":"http://localhost:3000"
    }
}

angular.json

        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "web-app:build",
            "proxyConfig": "proxy.conf.json" //追加
          },

server/src/index.ts

サーバー側にapiを作ります

app.get('/api',(req,res)=>{
    res.header('Content-Type', 'application/json; charset=utf-8');
    res.json({message:"こんにちは"});
});

app.module.ts

app.module.tsにHttpClientModuleを読み込みます

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule // 追加
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

apiのサービスを作ります

ng g service service/api

service/api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http:HttpClient) { }

  get hello$(){
    return this.http.get<Hello>('api/');
  }
}

export interface Hello{
  message:string;
}

app.component.ts

server側にgetを投げます

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService, Hello } from './service/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'web-app';
  hello:Observable<Hello>;


  constructor(private api:ApiService){}

  ngOnInit(){
    this.hello = this.api.hello$;
  }
}

app.component.html

<p *ngIf="hello|async as h">{{h.message}}</p>

実行

ng serve --open

localhost:4200にアクセスすると、server側でsendしたメッセージがangularのwebアプリ上で表示できました。
※ npm run dev でサーバー側も同時に動かしている必要があります。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?