簡體   English   中英

使用異步管道觀察角度

[英]Angular observable with async pipe

我正在創建我的第一個 Angular 應用程序,但我正在努力處理 observables(驚喜,驚喜)。 我的 HTML 標簽中有這個:

  <mwl-calendar-month-view
    *ngSwitchCase="'month'"
    [viewDate]="viewDate"
    [events]="observable | async"
    [activeDayIsOpen]="true"
  >

我嘗試在我的 observable 中使用異步管道。 為了更新我的 observable 的值,我進行了一些 REST 調用(在用戶單擊按鈕后),這是我處理點擊的方式:

  observable: Observable<CalendarEvent[]>;
  behaviourSubject: BehaviorSubject<CalendarEvent[]> = new BehaviorSubject([{
    title: 'title12345',
    start: new Date(),
    end: new Date()
  }]);

(...)

  onCreateCalendarEventClick() {
    let calendarEvent: CalendarEvent;
    calendarEvent = {
      title: (document.getElementById('calendarEventName') as HTMLInputElement).value,
      start: new Date((document.getElementById('calendarEventStartDate') as HTMLInputElement).value),
      end: new Date((document.getElementById('calendarEventEndDate') as HTMLInputElement).value),
      color: undefined
    };
    let calendarEventApi: CalendarEventApi;
    let calendarEventColor;
    if (calendarEvent.color) {
      calendarEventColor = calendarEvent.color;
    }
    calendarEventApi = {
      title: calendarEvent.title,
      start: ToApiMapper.formatDateTimeToApi(calendarEvent.start),
      end: ToApiMapper.formatDateTimeToApi(calendarEvent.end),
      color: ToApiMapper.mapColorToApi(calendarEventColor)
    };
    this.calendarService.saveCalendarEvent(calendarEventApi).subscribe( () => {
      this.fetchCalendarData();
    }, error => {
      this.alertService.displayAlert('saving calendar event failed: ' + error);
    });
  }


  private fetchCalendarData() {
      const calendarEvents: CalendarEvent[] = [];
      this.calendarService.fetchCalendarData(this.userService.getLoggedUser()).subscribe(calendarEventsApi => {
        calendarEventsApi.forEach(calendarEventApi => {
          const calendarEvent: CalendarEvent = {
            title: calendarEventApi.title,
            start: new Date(calendarEventApi.startDate),
            end: new Date(calendarEventApi.endDate),
            color: {
              primary: calendarEventApi.eventColour,
              secondary: calendarEventApi.eventColour
            }
          };
          calendarEvents.push(calendarEvent);
        });
        this.behaviourSubject.next(calendarEvents);
        this.observable = this.behaviourSubject.asObservable();
      });
  }

我試圖重現此處描述的行為: https : //malcoded.com/posts/angular-async-pipe/我如何理解代碼中發生的事情:從 REST 調用獲取響應正文后,我更新了行為主題將具有的下一個值. 然后我創建一個新的 observable,下一個值已經設置為我想要的響應。 然后我用 HTML 更新我的 observable。 HTML 應該重新加載(因為它監聽值的變化和我的 observable 的值剛剛改變)。 我的 REST 調用中的新值應該在 HTML 中可見。 我錯過了什么?

我相信您正在嘗試通過輸入傳遞您的 observable,我不確定是否會檢測到並發送更改。 我的建議是將您的 observable 存儲到您的服務中,以便可以通過依賴注入來獲取它。

這是一個向您展示如何使用主題的示例(我建議使用 BehaviorSubject)。 然后,您可以在日歷月視圖組件中注入您的服務並在那里使用您的 observable。 (僅供參考:observable 的標准是在末尾添加一個 $ 以便您知道它是一個)

@Injectable({
  providedIn: 'root'
})
export class UserService {

  private userList: User[];
  private userListSubject: BehaviorSubject<User[]> = new BehaviorSubject<User[]>([]);

  public constructor(private http: HttpClient) { }

  public usersList$(): Observable<User[]> {
    return this.userListSubject.asObservable();
  }

  public getAll$(): Observable<User[]> {
    return this.http.get<User[]>('/api/users').pipe(
      tap(userList => {
        this.userList = userList;
        this.userListSubject.next(this.userList);
      })
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM