Angular 進階介紹
Routing
Angular 的路由(Routing)允許應用在不同的視圖之間導航。首先,在 app-routing.module.ts
中配置路由:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyComponent } from './my-component/my-component.component';
const routes: Routes = [
{ path: 'my-path', component: MyComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<router-outlet></router-outlet>
來顯示路由內容。
Parameters & Route Guards
路由參數用於從 URL 傳遞數據。在路由配置中使用 :param
定義參數。
路由守衛是一種策略,用於控制對路由的訪問。例如,CanActivate
守衛決定是否可以導航到路由。
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class MyGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
// 邏輯判斷
return true;
}
}
{ path: 'my-path', component: MyComponent, canActivate: [MyGuard] }
Reactive Forms & Template
- 響應式表單(Reactive Forms):使用
FormControl
和FormGroup
來管理表單。import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'my-reactive-form', template: `...` }) export class MyReactiveFormComponent { myForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl('') }); }
- 模板驅動表單(Template-driven Forms):使用
ngModel
來創建和管理表單。<form> <input type="text" [(ngModel)]="name" name="name"> </form>
Validators
在表單中添加驗證規則,例如使用 Validators
進行必填、郵件格式等驗證。
import { FormControl, Validators } from '@angular/forms';
let email = new FormControl('', [Validators.required, Validators.email]);
import { FormControl } from '@angular/forms';
function customValidator(control: FormControl): {[key: string]: any} | null {
const isInvalid = /* 自定義邏輯 */;
return isInvalid ? { 'customError': { value: control.value } } : null;
}
HTTP Requests
在 app.module.ts
中引入 HttpClientModule
。使用 HttpClient
進行 GET、POST 等 HTTP 請求。
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data');
}
Observable & RxJS
Observable 是 RxJS 中的核心概念,用於處理非同步操作。它是一個數據流,可以被訂閱和處理。
import { Observable } from 'rxjs';
let observable = new Observable(subscriber => {
subscriber.next(1);
subscriber
.next(2);
setTimeout(() => {
subscriber.next(3);
subscriber.complete();
}, 1000);
});
observable.subscribe(value => console.log(value));
Service
在 Angular 中,服務(Service)用於封裝共享邏輯或數據。使用 @Injectable
裝飾器來創建服務。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
sharedData: string;
constructor() { }
setData(data: string) {
this.sharedData = data;
}
getData() {
return this.sharedData;
}
}
Interceptors
攔截器用於在請求發送前或響應接收後進行處理。例如,添加一個錯誤處理攔截器:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(error => {
// 處理錯誤
return throwError(error);
})
);
}
}
app.module.ts
中註冊攔截器:
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }