坂本  健一

坂本 健一

1651447140

Javaプログラミング 作成 コンパイル 実行方法

Javaプログラムの作成と実行方法について初心者の方でもわかりやすいように丁寧に解説しています^^

〇この動画で下記の3つのことができるようになります!(^^)b
 ①メモ帳を使ったJavaプログラムの作成
 ②Javaプログラムのコンパイル
 ③Javaプログラムの実行

途中出てくるよくわからないIT用語もなるべくわかりやすく解説しています^^
今回はこの用語を解説しました!
〇解説用語
 ・コンパイル

Javaは初心者がプログラミングを学ぶのにおすすめの言語です!
パソコン操作に慣れていない方、超初心者でもできるよう丁寧に解説しています^^
次はこちらで実際にJavaプログラミングに挑戦してみましょう^^/↓

使用環境:Windows10 64bit

#windows  #programming  #java 

What is GEEK

Buddha Community

Javaプログラミング 作成 コンパイル 実行方法
坂本  健一

坂本 健一

1651447140

Javaプログラミング 作成 コンパイル 実行方法

Javaプログラムの作成と実行方法について初心者の方でもわかりやすいように丁寧に解説しています^^

〇この動画で下記の3つのことができるようになります!(^^)b
 ①メモ帳を使ったJavaプログラムの作成
 ②Javaプログラムのコンパイル
 ③Javaプログラムの実行

途中出てくるよくわからないIT用語もなるべくわかりやすく解説しています^^
今回はこの用語を解説しました!
〇解説用語
 ・コンパイル

Javaは初心者がプログラミングを学ぶのにおすすめの言語です!
パソコン操作に慣れていない方、超初心者でもできるよう丁寧に解説しています^^
次はこちらで実際にJavaプログラミングに挑戦してみましょう^^/↓

使用環境:Windows10 64bit

#windows  #programming  #java 

中條 美冬

1650534962

DockerとDockerでMySQLを使用する方法-作成

このチュートリアルでは、MySQLをDockerおよびdocker-composeで使用する方法を段階的に説明し、理解しやすくします。 

DockerでMySQLを実行する

この初心者向けガイドでは、DockerHubの公式MySQLDockerイメージを使用します。公式のMySQLDockerイメージにはAlpineLinuxバージョンがありませんが、Debianバージョンも147 MB​​であり、Dockerイメージには大きすぎません。

公式イメージを使用してMySQL8.0コンテナを実行するには、次のコマンドを実行するだけです。

mkdir /tmp/mysql-data
docker run --name basic-mysql --rm -v /tmp/mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=ANSKk08aPEDbFjDO -e MYSQL_DATABASE=testing -p 3306:3306 -it mysql:8.0

Dockerを使用してMySQLを実行するために実行したコマンドを分析してみましょう。まず、MySQLのデータを保存するためにmysql-data呼び出されるディレクトリを作成しました。/tmp次に、次のdocker runコマンドを実行しました。

  • --nameコンテナに名前を付けるbasic-mysql
  • --rn停止時にコンテナを削除する
  • -v /tmp/mysql-data:/var/lib/mysqlコンテナの再起動時にデータを保持するために追加され、ホストマシンがそのまま再起動するとデータが消えます。/tmp
  • -e MYSQL_ROOT_PASSWORD=ANSKk08aPEDbFjDO -e MYSQL_DATABASE=testingrootユーザーのパスワードを設定し、という名前のデータベースを初期化するためtesting
  • -p 3306:3306ホストポート3306をコンテナポート3306にマップします。ポート3306はMySQLのデフォルトポートです。
  • -it mysql:8.0---すべてのログが表示され、Debianフレーバーを実行する公式のMySQLイメージバージョン8.0を使用しています。

以下に類似したものを表示して出力します。

2022-02-19 10:31:54+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
2022-02-19 10:31:54+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2022-02-19 10:31:54+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
2022-02-19 10:31:54+00:00 [Note] [Entrypoint]: Initializing database files
2022-02-19T10:31:54.932929Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.27) initializing of server in progress as process 44
2022-02-19T10:31:54.942400Z 0 [Warning] [MY-010159] [Server] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive
2022-02-19T10:31:54.952407Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-02-19T10:31:57.114688Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-02-19T10:31:58.994205Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-02-19T10:31:58.994241Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-02-19T10:31:59.204723Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2022-02-19 10:32:03+00:00 [Note] [Entrypoint]: Database files initialized
2022-02-19 10:32:03+00:00 [Note] [Entrypoint]: Starting temporary server
mysqld will log errors to /var/lib/mysql/568272f57c6b.err
mysqld is running as pid 95
2022-02-19 10:32:04+00:00 [Note] [Entrypoint]: Temporary server started.
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
2022-02-19 10:32:08+00:00 [Note] [Entrypoint]: Creating database testing

2022-02-19 10:32:08+00:00 [Note] [Entrypoint]: Stopping temporary server
2022-02-19 10:32:10+00:00 [Note] [Entrypoint]: Temporary server stopped

2022-02-19 10:32:10+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.

2022-02-19T10:32:10.353185Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.27) starting as process 1
2022-02-19T10:32:10.361054Z 0 [Warning] [MY-010159] [Server] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive
2022-02-19T10:32:10.379917Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-02-19T10:32:11.007492Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-02-19T10:32:11.362057Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-02-19T10:32:11.362123Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-02-19T10:32:11.366535Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2022-02-19T10:32:11.366644Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2022-02-19T10:32:11.372769Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2022-02-19T10:32:11.435797Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2022-02-19T10:32:11.435995Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.27'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.

MySQLサーバーが実行されているので、コンテナ内で次のコマンドを使用してMySQLコマンドを実行できます。

docker exec -it basic-mysql /bin/bash
#once inside the container 
mysql -uroot -p
#put/paste the password, and once inside MySQL CLI run
show databases;

以下のようになります。

コンテナ内でDockerを使用してMySQLを使用する

でコンテナを停止できますdocker stop basic-mysql

それはそれほど難しいことではありませんでしたが、コマンドのパラメーターを覚えるのは簡単ではなかったので、簡単だとは思いませんでした。もう1つの側面は、MySQLを単独で実行したことです。QuotesAPINode.jsアプリケーションとMySQLコンテナーの間にリンクはありません。これは、次のセクションで説明するように、docker-composeの宣言型の性質が非常に役立つ場合です。

docker-composeでMySQLを実行する

同じMySQL8.0をdocker-composeで実行するには、次の内容の新しいdocker-compose-mysql-only.ymlファイルを作成します。

version: '3.8'
services:
  db:
    image: mysql:8.0
    cap_add:
      - SYS_NICE
    restart: always
    environment:
      - MYSQL_DATABASE=quotes
      - MYSQL_ROOT_PASSWORD=mauFJcuf5dhRMQrjj
    ports:
      - '3306:3306'
    volumes:
      - db:/var/lib/mysql
      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
volumes:
  db:
    driver: local

上記のdocker-composeファイルには、次のことを理解する必要があります。

  1. 最新のものの1つであるdocker-composeファイルバージョン3.8を使用します。
  2. したがって、サービスとして定義dbします。各サービスは、新しいdockerrunコマンドと同等になります。
  3. 続いて、このDBサービスに公式のMySQL8.0イメージを使用するようにdocker-composeを指定します。
  4. いくつかの役に立たないエラーメッセージを抑制するためのcap_addセット。SYS_NICE
  5. 次に、docker-composeに、失敗した場合は常にこのコンテナーを再起動するように依頼します。
  6. その後、MySQLデータベースとrootユーザーのパスワード用に2つの環境変数を追加します。必要に応じて、別のユーザーを追加して、他のenv変数との特権を少なくすることができます。
  7. 次に、 MySQLサーバーがコンテナポートで実行されているため、ホストポート3306をコンテナポートにマップします。設定に応じて、ホストポートが変更される場合があります。33063306
  8. 次に、2つのボリュームを追加します。最初のボリュームは、以下のボリュームにマップされたDBボリュームdbです。これは基本的にdockerとdocker-composeにボリュームを管理するように指示します。次に、指定されたSQLファイルでデータベースを初期化するinit.sqlスクリプトを追加します。quotes

今回はdocker-composeを使用してMySQLコンテナを起動できます。

docker-compose -f docker-compose-mysql-only.yml up

以下のような出力が表示されます。

Starting nodejs-mysql_db_1 ... done
Attaching to nodejs-mysql_db_1
db_1  | 2022-02-19 10:55:55+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
db_1  | 2022-02-19 10:55:56+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1  | 2022-02-19 10:55:56+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
db_1  | 2022-02-19T10:55:56.381394Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.27) starting as process 1
db_1  | 2022-02-19T10:55:56.392419Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
db_1  | 2022-02-19T10:55:56.878693Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
db_1  | 2022-02-19T10:55:57.258522Z 0 [System] [MY-010229] [Server] Starting XA crash recovery...
db_1  | 2022-02-19T10:55:57.268530Z 0 [System] [MY-010232] [Server] XA crash recovery finished.
db_1  | 2022-02-19T10:55:57.305749Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
db_1  | 2022-02-19T10:55:57.305945Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
db_1  | 2022-02-19T10:55:57.309232Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db_1  | 2022-02-19T10:55:57.309330Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
db_1  | 2022-02-19T10:55:57.313177Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1  | 2022-02-19T10:55:57.374334Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
db_1  | 2022-02-19T10:55:57.374405Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.27'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.

出力は似ていますが、今回はdocker-composeで宣言型であるため、dockerコンテナー内でMySQLを実行する方がはるかに簡単なコマンドでした。
参考までに、このファイルを追加するためのPRも利用できます。次に、MySQLコンテナを既存のNode.jsアプリにリンクします。

docker-composeを使用してMySQLを既存のNode.jsアプリに追加する

この時点で、MySQLをdockerだけで実行し、次にdocker-composeで実行しました。これは、前の長いコマンドよりもはるかに簡単でした。それでも、パズルの1つのピース、つまりMySQLコンテナをアプリケーションにリンクするためのピースが欠落しています。この場合、Quotes用のNode.jsMySQLAPIになります。

この初心者向けチュートリアルではdocker-compose file、次の内容の新しいチュートリアルを追加します。

version: '3.8'
services:
  db:
    image: mysql:8.0
    cap_add:
      - SYS_NICE
    restart: always
    environment:
      - MYSQL_DATABASE=quotes
      - MYSQL_ROOT_PASSWORD=mauFJcuf5dhRMQrjj
    ports:
      - '3306:3306'
    volumes:
      - db:/var/lib/mysql
      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
  api:
    container_name: quotes-api
    build:
      context: ./
      target: production
    image: quotes-api
    depends_on:
      - db
    ports:
      - 3000:3000
    environment:
      NODE_ENV: production
      DB_HOST: db
      DB_PORT: 3306
      DB_USER: root
      DB_PASSWORD: mauFJcuf5dhRMQrjj
      DB_NAME: quotes
    links:
      - db
    volumes:
      - ./:/src
volumes:
  db:
    driver: local

このdocker-compose.ymlファイルは、上記のファイルのより長いバージョンのように見えます。主な違いは次のとおりです。

Dockerfileプロジェクトに含まれるものを使用するAPIサービスを追加します。API対象となる本番でサービスを構築します。興味に応じて、ビルドターゲットの使用法を説明するDockerマルチステージビルドの詳細を読むことができます。

次に、APIがDBコンテナに依存していることをdocker-composeに示します。その後、Node.jsを使用するExpress.jsアプリがポートで実行されるため、ホストポート3000をコンテナポートにマップします。30003000

続いて、Node.jsアプリがコンテナ内で実行されているMySQLデータベースに問題なく接続するために必要なすべての環境変数を設定します。その後、ローカルファイルをコンテナ内にマップして././srcすべてのファイル変更がコンテナ内に反映されるようにします。次に、APIコンテナがDBコンテナと通信できるように、両方のコンテナをリンクします。

このdocker-compose.ymlファイルは、参照用のプルリクエストとして利用できます。

でアプリケーションを実行するとdocker-compose up、次のような出力が表示されます。

Starting nodejs-mysql_db_1 ... done
Starting quotes-api        ... done
Attaching to nodejs-mysql_db_1, quotes-api
db_1   | 2022-02-19 11:08:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
db_1   | 2022-02-19 11:08:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1   | 2022-02-19 11:08:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.27-1debian10 started.
db_1   | 2022-02-19T11:08:36.469670Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.27) starting as process 1
db_1   | 2022-02-19T11:08:36.478201Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
db_1   | 2022-02-19T11:08:36.830802Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
db_1   | 2022-02-19T11:08:37.004513Z 0 [System] [MY-010229] [Server] Starting XA crash recovery...
db_1   | 2022-02-19T11:08:37.015831Z 0 [System] [MY-010232] [Server] XA crash recovery finished.
db_1   | 2022-02-19T11:08:37.063455Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
db_1   | 2022-02-19T11:08:37.063521Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
db_1   | 2022-02-19T11:08:37.064770Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
db_1   | 2022-02-19T11:08:37.064845Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
db_1   | 2022-02-19T11:08:37.068935Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1   | 2022-02-19T11:08:37.109788Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
db_1   | 2022-02-19T11:08:37.109836Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.27'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
quotes-api | 
quotes-api | > nodejs-mysql@0.0.0 start /src
quotes-api | > node ./bin/www
quotes-api | 

でブラウザを押すとhttp://localhost:3000/quotes、次のようなものが表示されます。

既存のNode.jsアプリケーションでDockerでMySQLを使用する

素晴らしい!Node.js Express Quotes APIは、dockerコンテナー内で実行され、docker-composeに接続されているローカルMySQLと適切に通信しています。データはinit.sqlスクリプトから取得されたため、引用符はAPI応答で利用できます。

このガイドでは、docker run、docker-compose、最後にNode.jsアプリケーションとのリンクを段階的に実行してMySQLを実行する方法を説明しました。

宇野  和也

宇野 和也

1653164940

【Python初心者〜中級者向け】プログラミングの3つの基本構造、実行方法

この動画では、プログラムの3つの基本構造と、プログラムの実行方法について説明します。
まずは、プログラムの3つの基本構造について説明します。
「順次進行」「条件分岐」「繰り返し」です。
この3つの基本構造を使えば、複雑なプログラムを作ることができます。
ここでは、最もシンプルな「順次進行」について、プログラムを実行しながら確認します。
VSCodeとJupyter Labを使って説明します。

▼目次
00:00 はじめに
00:17 プログラムの3つの基本構造について
02:29 あいだに
02:51 VSCodeでPythonファイルを実行(作成、保存、実行)
05:48 コメントアウトの使い方
06:17 Jupyter LabでPythonファイルを実行
07:25 おわりに

▼書き起こし
https://kino-code.com/python_introductory-and-applied03/

▼書き起こし
## プログラムの基本構造
プログラムでは、インターネットのサービスや人工知能、スマホアプリ、ゲームなどいろいろなものを作ることができます。
そう聞くと、プログラムでは複雑なことをしているイメージをもつかもしれません。
でも、プログラムの動きはシンプルです。
動きは3つだけです。
「順次進行」「条件分岐」「繰り返し」です。
この3つの動きのことをまとめて、プログラムの基本構造と言ったり、制御構造、制御フローと言ったりします。
この3つの基本構造を使えば、複雑なプログラムを作ることができます。
そして、この3つは、どのプログラミング言語にもあります。
順に説明していきます。

まずは、「順次進行」です。
順次進行とは、プログラムが書かれている上から順に処理をしていくというプログラムの構造です。
プログラムの最も基本的な動きになります。
プログラムのソースコードの記述が、上から順に、処理A、処理B、処理Cと記述されていたら、処理も上から順に、処理A、処理B、処理Cと処理されていきます。
例えば、ソースコードが「おはよう」「こんにちは」「こんばんは」とパソコンの画面上に表示させるプログラムだったとします。
プログラムを実行すると、上から順に、「おはよう」「こんにちは」「こんばんは」と表示されます。

次に、「条件分岐」です。
条件分岐とは、特定の条件のときはAという処理、そうじゃないときはBという処理をするプログラム構造です。
例えば、あるデータの値が20以上なら「おとな」と画面上に表示させて、20未満なら「こども」と表示させるといった処理ができます。

繰り返しとは、決まった回数や条件を満たすまで同じ処理を繰り返すプログラム構造です。
繰り返しは、反復処理といったりもします。
例えば、「こども」という文字を繰り返し20回表示させたい場合などに使います。
他にも、あるデータに1ずつ足していき、そのデータが20未満であれば「こども」を表示させる。20以上になったら、繰り返し処理を終わらせるということができます。

## VSCodeでのプログラムの実行方法
続いて、プログラムの実行方法について説明します。
例として、パソコン上に挨拶の「Good morning(おはよう)」「Good afternoon(こんにちは)」「Good evening(こんばんは)」と表示させるプログラムを記述・実行してみましょう。
はじめに、VSCodeで実行してみましょう。
まず、VScodeを起動します。
これがファイル管理のための「エクスプローラ」です。クリックします。
「フォルダを開く」をクリック
デスクトップに「MyPython」というファルダを作りましょう。
選択して開く。
MyPythonのフォルダが選択されています。Pythonファイルを作ってみましょう。
英語で挨拶は、Greetingといいます。ファイル名を「Greeting.py」とします。
これでPythonファイルの作成はおわりです。
このレッスンでは、Pythonのプログラムの書き方や、実行のやり方を把握してもらうだけでよいです。
プログラムの意味については、あとに続くレッスンで説明するので、今はプログラムの意味は、「ルール」や「きまり」だと思って進めてください。
早速、コンピューターに挨拶を表示させるコードを書いていきましょう。
(続く)


#python  #vscode  #jupyterlab 

中條 美冬

1660136288

Angular Firebase CRUD アプリを作成する方法 (作成、更新、読み取り、削除)

本日の投稿では、Angular 8 アプリを使用して Firebase で CRUD アクティビティを表示するサンプル アプリを作成します。

まず、Firebase データベースを Angular アプリに接続する必要があります。Angular アプリケーションの接続について理解していない場合は、ここで確認できます。

ステップ 1: サービス ファイルを作成する

次に、Angular 8 アプリで実行するすべての操作について、firebase にリクエストを行うロジックを持つサービス ファイルを作成します。 

Angular CLI で以下のコマンドを実行して、認証サービス ファイルを生成します。

ng g s services/document
import { Injectable } from '@angular/core';
import { Document } from '../_model/document';
import { AngularFirestore } from "@angular/fire/firestore";
 
@Injectable({
providedIn: 'root'
})
 
export class DocumentService {
 
constructor(private firestore: AngularFirestore) {}
 
/* Add Document */
AddDocument(document: Document) {
return new Promise<any>((resolve, reject) => {
this.firestore.collection("documents").add(document)
.then(res => {
resolve(res);
}, err => reject(err));
});
}
 
// /* Get Document */
GetDocument(id: string) {
return this.firestore.collection("documents").doc(id).snapshotChanges();
}
 
/* Get Document list */
GetDocumentList() {
return this.firestore.collection("documents").snapshotChanges();
}
 
// /* Update Document */
updateDocument(userKey, value){
return this.firestore.collection('documents').doc(userKey).set(value);
}
 
// /* Delete Document */
DeleteDocument(data) {
return this.firestore.collection("documents").doc(data.payload.doc.id)
.delete();
}
}

また、サービス ファイルを app.module.ts ファイルに追加します。

ステップ 2: 一覧表示、追加、編集タスク用のコンポーネントを作成する

ng g c components/add-document
ng g c components/edit-document
ng g c components/document-list

ステップ 3: ドキュメント追加コンポーネント ファイルを更新する

以下のコードを add-document.ts ファイル内に配置します

import { Component, OnInit } from '@angular/core';
import { DocumentService } from './../../services/document.service';
import { FormGroup, FormControl, Validators, NgForm } from "@angular/forms";
import { Router } from '@angular/router';
 
@Component({
selector: 'app-add-document',
templateUrl: './add-document.component.html',
styleUrls: ['./add-document.component.css']
})
export class AddDocumentComponent implements OnInit {
addDocumentForm:FormGroup;
constructor(
private _documentService : DocumentService,
private router : Router
) { }
 
ngOnInit() {
this.addDocumentForm = new FormGroup ({
title: new FormControl (null, [Validators.required, Validators.maxLength(200)]),
description: new FormControl (null, [Validators.required, Validators.maxLength(200)]),

author: new FormControl (null, [Validators.required, Validators.maxLength(200)])
})
}
 
submitDocument(form):void{
this._documentService.AddDocument(form.value);
this.router.navigate(['document-list']);
}
 
}

上記のファイルには、リアクティブ フォームと submitDocument 関数を備えた基本的なコンポーネントがあり、フォームからの送信リクエストを処理し、それに応じて firebase にリクエストを送信します。

add-document.ts ファイルを更新する

<section>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 form-wrapper">
<h3 class="text-center">Add Document</h3>
<form [formGroup]="addDocumentForm" novalidate>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="title" formControlName="title">
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" name="description" class="form-control" id="description" formControlName="description">
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" id="author" name="author" formControlName="author">
</div>
<button type="submit" [disabled]="!addDocumentForm.valid" class="btn btn-primary"
(click)="submitDocument(addDocumentForm)">Submit</button>
</form>
</div>
</div>
</div>
</section>

上記のファイルには、3 つの入力フィールドと送信ボタンのあるフォームがあります。

ステップ 4: 編集ドキュメント コンポーネント ファイルを更新する

以下のコードを edit-document.ts ファイルに入れます

import { Component, OnInit } from '@angular/core';
import { DocumentService } from './../../services/document.service';
import { FormGroup, FormControl, Validators, NgForm } from "@angular/forms";

import { ActivatedRoute, Router } from '@angular/router';
 
@Component({
selector: 'app-edit-document',
templateUrl: './edit-document.component.html',
styleUrls: ['./edit-document.component.css']
})
export class EditDocumentComponent implements OnInit {
editDocumentForm:FormGroup;
id:string;
 
constructor(
private _document : DocumentService,
private route : ActivatedRoute,
private router : Router
) { }
 
ngOnInit() {
this.editDocumentForm = new FormGroup ({
title: new FormControl (null, [Validators.required, Validators.maxLength(200)]),
description: new FormControl (null, [Validators.required, Validators.maxLength(200)]),

author: new FormControl (null, [Validators.required, Validators.maxLength(200)])
});
 
this.id = this.route.snapshot.paramMap.get("id");
this.getDocument();
}
 
getDocument() {
this._document.GetDocument(this.id)
.subscribe(res => {
this.editDocumentForm.controls['title'].setValue (res.payload.data()['title']);
this.editDocumentForm.controls['description'].setValue (res.payload.data()['description']);
this.editDocumentForm.controls['author'].setValue (res.payload.data()['author']);
});
}
 
submitDocument(form){
this._document.updateDocument(this.id, form.value)
.then(
res => {
this.router.navigate(['document-list']);
}
)
}
 
}

編集文書ファイルの更新

<section>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 form-wrapper">
<h3 class="text-center">Edit Document</h3>
<form [formGroup]="editDocumentForm" novalidate>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="title" formControlName="title">
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" name="description" class="form-control" id="description" formControlName="description">
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" id="author" name="author" formControlName="author">
</div>
<button type="submit" [disabled]="!editDocumentForm.valid" class="btn btn-primary"
(click)="submitDocument(editDocumentForm)">Submit</button>
</form>
</div>
</div>
</div>
</section>

ステップ 5: ドキュメント リスト コンポーネント ファイルを更新する

以下のコードを document-list.component.ts ファイルに追加します

import { Component, OnInit } from '@angular/core';
import { DocumentService } from './../../services/document.service';
 
@Component({
selector: 'app-document-list',
templateUrl: './document-list.component.html',
styleUrls: ['./document-list.component.css']
})
export class DocumentListComponent implements OnInit {
documents;
id;
constructor(
private _documentService : DocumentService,
) { }
 
ngOnInit() {
this.getDocumentList();
}
 
getDocumentList = () =>
this._documentService
.GetDocumentList()
.subscribe(res => {
this.documents = res;
});
 
deleteDocument = data => this._documentService.DeleteDocument(data);
}

以下のコードを document-list.component.html ファイルに追加します

<section>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 form-wrapper">
<h3 class="text-center">Document List</h3>
<table>
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Author</th>
<td></td>
</tr>
</thead>
 
<tbody>
<tr *ngFor="let document of documents">
<td>{{ document.payload.doc.data().title }}</td>
<td>{{ document.payload.doc.data().description }}</td>
<td>{{ document.payload.doc.data().author }}</td>
<td>
<button class="btn btn-primary" [routerLink]="['/edit-document/', document.payload.doc.id]"><i class="fa fa-pencil"></i></button>
<button class="btn btn-primary" (click)="deleteDocument(document)"><i class="fa fa-trash"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>

ステップ 6: 異なるルートで異なるコンポーネントを提供するルートを作成します。

 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
import { AddDocumentComponent } from './components/add-document/add-document.component';

import { EditDocumentComponent } from './components/edit-document/edit-document.component';

import { DocumentListComponent } from './components/document-list/document-list.component';
 
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'add-document' },
{ path: 'add-document', component: AddDocumentComponent },
{ path: 'edit-document/:id', component: EditDocumentComponent },
{ path: 'document-list', component: DocumentListComponent }
];
 
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
 

ステップ 7: app.module.ts ファイルを更新する

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
/*Firebase */
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from "@angular/fire/firestore";
import { environment } from 'src/environments/environment';
 
/*Components */
import { AddDocumentComponent } from './components/add-document/add-document.component';
import { EditDocumentComponent } from './components/edit-document/edit-document.component';
import { DocumentListComponent } from './components/document-list/document-list.component';
 
/*Service */
import { DocumentService } from './services/document.service';
 
@NgModule({
declarations: [
AppComponent,
AddDocumentComponent,
EditDocumentComponent,
DocumentListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule
],
providers: [DocumentService],
bootstrap: [AppComponent]
})
export class AppModule { }

上記のファイルでは、必要な firebase パッケージ、作成されたサービス ファイル、およびコンポーネント ファイルがここでブートストラップされていることがわかります。

ステップ 8: アプリを実行する

以下のコマンドで上記のアプリを実行します。

ng serve

これで、ブラウザでアプリを確認できます。

いくつかの手順を実行した後、Angular Firebase CRUD アプリが正常に作成されました。