
前の記事では、
サービスは API リクエストの処理に使用できるだけでなく、
この記事で説明するnotificationの実装など、他の用途もあると述べました。 【おすすめ関連チュートリアル:「Angularチュートリアル」】
レンダリングは以下の通りです。

UI は後で調整できる
ので、段階的に見てみましょう。
サービスを追加するには、
app/servicesにnotification.service.tsサービス ファイルを追加し (コマンド ラインを使用して生成してください)、関連コンテンツを追加します:
// notification.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
// 通知ステータスの列挙体 export enum NoticeStatus {
プロセス = 「進捗」、
成功=「成功」、
失敗=「失敗」、
終了 = 「終了」
}
@Injectable({
提供対象: 'ルート'
})
エクスポートクラスNotificationService {
プライベート通知: Subject<NotificationStatus> = new Subject();
パブリックメッセージオブジェクト: 任意 = {
主要な: ''、
二次: ''
}
// 監視可能なものに変換します public getNotification(): Observable<NotificationStatus> {
this.notify.asObservable() を返します。
}
// 通知が進行中 public showProcessNotification() {
this.notify.next(通知ステータス.プロセス)
}
// 成功通知 public showSuccessNotification() {
this.notify.next(NotificationStatus.Success)
}
//終了通知 public showEndedNotification() {
this.notify.next(通知ステータス.終了)
}
// 変更情報 public changePrimarySecondary(primary?: string, Secondary?: string) {
this.messageObj.primary = プライマリ;
this.messageObj.secondary = セカンダリ
}
コンストラクター() { }
分かりやすいでしょうか…
notify
notify監視可能なオブジェクトにして、様々なステータス情報を公開します。
コンポーネントを作成するには、
パブリック コンポーネントが保存されているapp/componentsに新しいnotificationコンポーネントを作成します。
したがって
、次の構造が得られます。
§── notification.component.html // ページのスケルトン §── notification.component.scss // ページ独自のスタイル §── notification.component.spec.ts // テストファイル └── notification.component.ts // で
notificationのスケルトンを定義する
JavaScript ファイル:
<!-- notification.component.html -->
<!--通知の手動クローズをサポート-->
<button (click)="closeNotification()">閉じる</button>
<h1>リマインダーの内容: {{ メッセージ }}</h1>
<!-- 主要な通知情報をカスタマイズします-->
<p>{{primaryMessage }}</p>
<!-- 二次通知情報をカスタマイズします -->
<p>{{ SecondaryMessage }}</p>次に、スケルトンを変更して次のスタイルを追加します:
// notification.component.scss
:ホスト {
位置: 固定;
上: -100%;
右: 20ピクセル;
背景色: #999;
ボーダー: 1px ソリッド #333;
境界半径: 10px;
幅: 400ピクセル;
高さ: 180ピクセル;
パディング: 10px;
// ここでの active の内容に注意してください。 &.active {
上: 10ピクセル;
}
&。成功{}
&。進捗 {}
&。失敗 {}
&.終了 {}
success、progress、failure、および
success, progress, failure, endedの 4 つのクラス名は、通知サービスによって定義された列挙に対応しており、独自の設定に従って関連するスタイルを追加できます。
最後に、動作を制御するjavascriptコードを追加します。
// notification.component.ts
import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
//新しい知識ポイント rxjs
import { サブスクリプション } から 'rxjs';
'rxjs/operators' から {debounceTime} をインポートします。
//関連サービスを導入します import { NoticeStatus, NoticeService } from 'src/app/services/notification.service';
@成分({
セレクター: 'アプリ通知',
templateUrl: './notification.component.html',
styleUrls: ['./notification.component.scss']
})
エクスポート クラス NoticeComponent は OnInit、OnDestroy を実装します {
// アンチシェイク時間、読み取り専用 private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200;
protected notificationSubscription!: サブスクリプション;
プライベートタイマー: 任意 = null;
パブリックメッセージ: 文字列 = ''
// 通知サービスの列挙情報のマッピング private ReflectObj: any = {
進行状況: "進行中"、
成功: 「成功」、
失敗: 「失敗」、
終わった:「終わり」
}
@HostBinding('class') notificationCssClass = '';
public PrimaryMessage!: 文字列;
パブリックセカンダリメッセージ!: 文字列;
コンストラクタ(
プライベート notificationService: 通知サービス
) { }
ngOnInit(): void {
this.init()
}
パブリック init() {
//関連するサブスクリプション情報を追加します this.notificationSubscription = this.notificationService.getNotification()
。パイプ(
debounceTime(this.NOTIFICATION_DEBOUNCE_TIME_MS)
)
.subscribe((通知ステータス: 通知ステータス) => {
if(通知ステータス) {
this.resetTimeout();
//関連スタイルを追加 this.notificationCssClass = `active ${ notificationStatus }`
this.message = this.reflectObj[通知ステータス]
// カスタム プライマリ メッセージを取得します this.primaryMessage = this.notificationService.messageObj.primary;
// カスタム セカンダリ情報を取得します this.secondaryMessage = this.notificationService.messageObj.secondary;
if(notificationStatus === 通知ステータス.プロセス) {
this.resetTimeout()
this.timer = setTimeout(() => {
this.resetView()
}、1000)
} それ以外 {
this.resetTimeout();
this.timer = setTimeout(() => {
this.notificationCssClass = ''
this.resetView()
}、2000)
}
}
})
}
プライベートresetView(): void {
this.message = ''
}
// タイマーを閉じます private resetTimeout(): void {
if(this.timer) {
clearTimeout(this.timer)
}
}
// 通知を閉じる public closeNotification() {
this.notificationCssClass = ''
this.resetTimeout()
}
// コンポーネントは破棄されます ngOnDestroy(): void {
this.resetTimeout();
//すべてのサブスクリプション メッセージをキャンセルします this.notificationSubscription.unsubscribe()
}
ここでは、 rxjsの知識ポイントを紹介します。 RxJSは、 Observablesを使用したリアクティブ プログラミング ライブラリであり、非同期またはコールバック ベースのコードを簡単に作成できます。これは素晴らしいライブラリです。今後のいくつかの記事で詳しく説明します。
ここでは、 debounceアンチシェイク関数を使用します。関数アンチシェイクとは、イベントがトリガーされた後、n 秒以内にイベントが再度トリガーされた場合、関数の実行時間が 1 回だけ実行されることを意味します。再計算されました。簡単に言うと、アクションが連続してトリガーされると、最後に実行されたものだけが実行されます。
ps:
throttleスロットル機能:一定時間内に 1 回だけ実行される機能を制限します。
面接中に、面接官は次のように尋ねます...
呼び出し
これはグローバル サービスであるため、このコンポーネントをapp.component.htmlで呼び出します。
// app.component.html <ルーター アウトレット></ルーター アウトレット> <app-notification></app-notification>
デモンストレーションを容易にするために、デモンストレーションを簡単にトリガーできるボタンをuser-list.component.htmlに追加します。
// user-list.component.html <button (click)="showNotification()">通知を表示をクリック</button> すると、
関連するコードがトリガーされます:
// user-list.component.ts
import { NoticeService } から 'src/app/services/notification.service';
// ...
コンストラクタ(
プライベート notificationService: 通知サービス
) { }
// 通知を表示 showNotification(): void {
this.notificationService.changePrimarySecondary('一次情報1');
this.notificationService.showProcessNotification();
setTimeout(() => {
this.notificationService.changePrimarySecondary('一次情報2', '二次情報2');
this.notificationService.showSuccessNotification();
}、1000)
この時点で完了です。 notification関数のシミュレーションは正常に完了しました。実際のニーズに応じて関連するサービス コンポーネントを変更し、ビジネス ニーズに合わせてカスタマイズできます。社内で使用するシステムを開発している場合は、成熟した UI ライブラリを使用することをお勧めします。これにより、さまざまなコンポーネントやサービスがカプセル化され、開発時間を大幅に節約できます。