【Angular】コンポーネント間共通定数を定義(改善Ver)

謎のプリン語る。
プログラミングの役立つ情報とか、どうでもいい雑談とか書いてます。
一人書く人増えました。

【Angular】コンポーネント間共通定数を定義(改善Ver)

みやびプリン 500 316

500 320

【Angular】コンポーネント間共通定数を定義(改善Ver) - サムネイル

※この記事は4年以上前の記事です。
現在は状況が異なる可能性がありますのでご注意ください。

どうも、お昼、行こうとしたスープカレー屋さんが激混みで入れず、不機嫌なみやびです。

どうでもいいってな。

さて、表記の件。
前回同じものやったのだが、
【Angular】コンポーネント間共通定数を定義 / 今日のプリン言 | イラストポートフォリオWebサイト - 月の高いところ
今見ると、Angular的にはそうするしかなくても、TypeScript的にはナンセンスな定義だったので、
Linterにも注意されない改善案を出しておこうと思って、今回のエントリーだ。
主にまずかったのは下記の部分。

import { Component, OnInit } from '@angular/core';
// 定数ファイルをクラス名でインポート
import { AppConst } from 'app.const.tsがあるディレクトリまでの相対パス/app.const';

@Component({
  selector: 'app-sitetop',
  templateUrl: './sitetop.component.html',
  styleUrls: [
    './sitetop.component.scss'
  ]
})
export class SitetopComponent implements OnInit {
  // AppClass型変数を定義
  AppConstClass: AppConst;
  // 最終的に使用する型なしの変数定義
  AppConst;
  constructor() {
    // スタティックで使うのに、newさせてる
    // クラスがconstructor定義なしだから、()つけれないが、TypeScript的に怒られるに決まってる。
    // というふうにとにかくいろんな面でダメダメ
    this.AppConstClass = new AppConst;
    // インスタンスのメソッドを実行し、staticなクラスを代入
    this.AppConst = this.AppConstClass.main();
  }

  ngOnInit() {
  }
}

ようは、静的なクラスとして定義してんのに、newでインスタンス生成してるとことか、もういろいろダメなわけだ。

じゃぁ、どうするかというと、interfaceを使うってわけだよ。

export interface AppConstInterface {
  readonly PAGE_CHARSET: string;
  readonly AUTHOR: string;
  readonly COPYRIGHT: string;
  readonly PAGE_TITLE: string;
  readonly APP_TITLE: string;
}

export const AppConst: AppConstInterface = {
  PAGE_CHARSET: 'utf-8',
  AUTHOR: 'みやびプリン',
  COPYRIGHT: 'Highmoon CO., LTD.',
  PAGE_TITLE: '月の高いところ',
  APP_TITLE: 'イラストサイト'
}

要は、変数の型として、readonlyにしちゃって、変数として定義しちゃうってわけ。
コンポーネント、ならびにビューで使うには下記だ。

import { Component, OnInit } from '@angular/core';
// 定数ファイルをクラス名でインポート
import { AppConst, AppConstInterface } from 'app.const.tsがあるディレクトリまでの相対パス/app.const';

@Component({
  selector: 'app-sitetop',
  templateUrl: './sitetop.component.html',
  styleUrls: [
    './sitetop.component.scss'
  ]
})
export class SitetopComponent implements OnInit {
  // AppConstInterface型変数を定義
  public AppConst: AppConstInterface = AppConst;
  constructor() {
    // あとはなんも考えずに、テンプレート内で使用可能
  }

  ngOnInit() {
  }
}

ほんとに、interface便利すぎやで。

CIA/公認内部監査人資格 アビタス - メイン

トラックバック(0)

トラックバックURL:

コメントする

ページトップへ戻る