Angular 環境變數

嵌套路由

1
<router-outlet></router-outlet>

this.router.navigate([‘users’]); 切換至頁面

專案內 src 新增environment 資料夾內environment.ts 與 environment.development.ts
environment.ts檔案內新增

1
2
3
4
5
export const environment = {
production:false,
webSit:'網址',
weatherApiKey: '密碼',
};

environment.development.ts檔案內新增

1
2
3
4
5
export const environment = {
production: true
webSit:'網址',
weatherApiKey: '密碼',
};

在頁面中使用

src/app/app.component.ts 內

  • 引入environment
  • 引入environment
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
+ import { environment } from '../environments/environment';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'vite_angular19_todo_project';

+ ngOnInit(): void {
+ console.log(environment.production ? 'Production' : '開發中')
+ }
}

環境變數github