Observable 基礎與初始化 - 附 Vue 比較

Observable vs Vue Reactive

Vue 的資料響應方式

// Vue 3 的寫法
const count = ref(0)
const user = reactive({
  name: 'John',
  age: 20
})

// 監聽變化
watch(count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`)
})

Angular 的 Observable 方式

// Angular 的寫法
private countSubject = new BehaviorSubject<number>(0);
count$ = this.countSubject.asObservable();

// 監聽變化
this.count$.subscribe(newValue => {
  console.log(`Count changed to ${newValue}`)
});

資料獲取比較

Vue 的 API 調用

// Vue 使用 async/await
async function getLocations() {
  const response = await axios.get('/api/locations');
  this.locations = response.data;
}

// 或使用 Promise
axios.get('/api/locations')
  .then(response => {
    this.locations = response.data;
  });

Angular 的 Observable 方式

// Angular Service
getLocations(): Observable<Location[]> {
  return this.http.get<Location[]>('/api/locations');
}

// Component 中使用
locations$ = this.locationService.getLocations();

模板渲染比較

Vue 模板

<!-- Vue 的 v-for -->
<div v-for="location in locations" :key="location.id">
  {{ location.name }}
</div>

Angular 模板

<!-- Angular 的 async pipe -->
@for (location of locations$ | async; track location.id) {
  <div>{{ location.name }}</div>
}

表單處理比較

Vue 的表單處理

// Vue 的雙向綁定
const searchTerm = ref('')

// 監聽變化
watch(searchTerm, (newValue) => {
  search(newValue);
})

Angular 的表單處理

// Angular 的表單控制
searchControl = new FormControl('');

// 監聽變化
searchResults$ = this.searchControl.valueChanges.pipe(
  debounceTime(300),
  switchMap(term => this.search(term))
);

狀態管理比較

Vue (Pinia/Vuex)

// Pinia Store
export const useLocationStore = defineStore('location', {
  state: () => ({
    locations: []
  }),
  actions: {
    async fetchLocations() {
      const data = await api.getLocations()
      this.locations = data
    }
  }
})

Angular Service

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  private locationsSubject = new BehaviorSubject<Location[]>([]);
  locations$ = this.locationsSubject.asObservable();

  fetchLocations() {
    this.http.get<Location[]>('/api/locations')
      .subscribe(data => this.locationsSubject.next(data));
  }
}

主要差異總結

  1. 資料處理方式

    • Vue:使用 ref/reactive 進行響應式處理

    • Angular:使用 Observable 流處理

  2. 異步處理

    • Vue:主要使用 Promise 和 async/await

    • Angular:使用 Observable 和 RxJS 操作符

  3. 模板更新

    • Vue:自動追蹤依賴並更新

    • Angular:需要使用 async pipe 處理 Observable

  4. 狀態管理

    • Vue:通常使用 Pinia/Vuex

    • Angular:使用 Service + Observable

Last updated