"Subject" rxjs ning keyingi so'roviga http-chaqiruv bekor qilinadi

Menda foydalanuvchi chiqib ketish uchun dastur mavjud, men RESTning oxirgi nuqtasiga urishim kerak. Mening burchaklarimning 2-qismida quyidagi xizmatlarni bajaraman:

@Injectable()
export class AuthService {

  private authEvents: Subject;

  constructor(private http: Http) {
    this.authEvents = new Subject();
  }

  login(email: string, password: string): Observable {
    const url = 'rest/auth/login';
    const body = {
      email: email,
      password: password
    };
    return this.http.post(url, body)
      .do((res: Response) => {
        localStorage.setItem('currentUser', JSON.stringify(res.json()));
        this.authEvents.next(true);
      });
  }

  logout(): Observable {
    const url = 'rest/auth/logout';
    return this.http.post(url, {})
      .do((res: Response) => {
        localStorage.removeItem('currentUser');
        console.log('hereee!');
        this.authEvents.next(false);
      });
  }

  isSignedIn(): boolean {
    return localStorage.getItem('currentUser') !== null;
  }

  get events(): Observable {
    return this.authEvents;
  }

}

Bu erda nima qilishga harakat qilayotganimni tushuntirib beray. Mening komponentimda obuna bo'layotgan bir authEvents mavzusi bor:

ngOnInit() {
  this.isSignedIn = this.authService.isSignedIn();
  this.authService.events.subscribe(() => {
    this.isSignedIn = this.authService.isSignedIn();
  });
}

Foydalanuvchi sessiya tugmachasini bossa, ushbu komponentda quyidagi funktsiyani chaqiraman:

logout() {
  this.authService.logout()
    .subscribe(() => {
      this.router.navigate(['/home']);
    }, e => this.handleError(e));
}

Muammo shundaki, brauzer tizimga chiqish qo'ng'iroqlari hali tugamagan bo'lsa ham, uni uyga yo'naltiradi. Shunday qilib, samarali, ba'zan frontend muvaffaqiyatli chiqadi, va ba'zan u yo'q! Men bu erda noto'g'ri ish qilyapmanmi?

Eslatma: http chaqiruvi sodir bo'lgandan beri orqa tomondagi sessiya har doim tashqariga chiqadi. Shunga erishish uchun Observables (umuman rxjs) ni qanday ishlatishni ko'rishni xohlayman, garchi juda ko'p muammolar bo'lsa, unda Va'dalar ishlatilishi mumkin.

1
.Do() ni ehtiyotkorlik bilan ishlatish, chunki u yon ta'sirlarga va ko'pincha disk raskadrovka uchun ishlatiladi. Bundan tashqari, iloji boricha issiq kuzatiladigan narsalardan qochishga harakat qilaman. Ilovangizni biroz murakkablashtirishi mumkin.
qo'shib qo'ydi muallif DarkNeuron, manba

6 javoblar

Mavzu bilan sizda shunday vaziyat mavjudki, emissiya faqatgina kelgusi abonentlar tomonidan emas, balki abonentlar tomonidan qabul qilinadi. Mening taxminimcha, bu sizning muammosiz bu erda - sizning hayotingizni osonlashtirishi uchun BehaviorSubject dan foydalanishingiz mumkin, u hozirgi qiymatini har qanday kelajakdagi abonentga qaytaradi, shuning uchun har qanday poyga shartlari haqida qayg'urishingiz kerak.

However: Strictly seen it will not be an event any more, but more of a state, which is what I would suggest to use anyways in your case - since with RxJS you can leverage the power of states over events.

@Injectable()
export class AuthService {

  public currentUser$: BehaviorSubject = new BehaviorSubject(null);//initial state is "null" => user is not logged in
  private isSignedIn$: Observable = currentUser$.map(user => Boolean(user)).share();

  constructor(private http: Http) {
    this.authEvents = new Subject();
  }

  login(email: string, password: string): Observable {
    const url = 'rest/auth/login';
    const body = {
      email: email,
      password: password
    };
    return this.http.post(url, body)
      .do((res: Response) => {
        localStorage.setItem('currentUser', JSON.stringify(res.json()));
        this.currentUser$.next(res.json());//will automatically trigger the logged-in state as well 
      });
  }

  logout(): Observable {
    const url = 'rest/auth/logout';
    return this.http.post(url, {})
      .do((res: Response) => {
        localStorage.removeItem('currentUser');
        console.log('hereee!');
        this.currentUser$.next(null);//will automatically trigger the logged-in state as well 
      });
  }
}

Komponentingizda

private desotryed$: Subject = new Subject();

ngOnInit() {
  this.authService.isSignedIn$
    .takeUntil(this.desotryed$)//to prevent memory leaks through a perpetual subscription
    .subscribe(isSignedIn => {
      this.isSignedIn = isSignedIn;
    });
}

ngOnDestroy() {
  this.desotryed$.next(true);
}

Since the RxJS5 docs are not including the BehaviorSubject yet, here is a link to the old docs: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md

2
qo'shib qo'ydi
Bu ish ishonaman (rahmat!), Lekin men javob berganim boshqa yondashuv bilan yugurdim. Logout() chaqiruvi bilan "$ event.preventDefault ()" ni qo'shish kabi ko'rinadi. Menga nima uchun u ishlaydi, deb ayta olasizmi?
qo'shib qo'ydi muallif Saket Mehta, manba

Mavzu bilan sizda shunday vaziyat mavjudki, emissiya faqatgina kelgusi abonentlar tomonidan emas, balki abonentlar tomonidan qabul qilinadi. Mening taxminimcha, bu sizning muammosiz bu erda - sizning hayotingizni osonlashtirishi uchun BehaviorSubject dan foydalanishingiz mumkin, u hozirgi qiymatini har qanday kelajakdagi abonentga qaytaradi, shuning uchun har qanday poyga shartlari haqida qayg'urishingiz kerak.

However: Strictly seen it will not be an event any more, but more of a state, which is what I would suggest to use anyways in your case - since with RxJS you can leverage the power of states over events.

@Injectable()
export class AuthService {

  public currentUser$: BehaviorSubject = new BehaviorSubject(null);//initial state is "null" => user is not logged in
  private isSignedIn$: Observable = currentUser$.map(user => Boolean(user)).share();

  constructor(private http: Http) {
    this.authEvents = new Subject();
  }

  login(email: string, password: string): Observable {
    const url = 'rest/auth/login';
    const body = {
      email: email,
      password: password
    };
    return this.http.post(url, body)
      .do((res: Response) => {
        localStorage.setItem('currentUser', JSON.stringify(res.json()));
        this.currentUser$.next(res.json());//will automatically trigger the logged-in state as well 
      });
  }

  logout(): Observable {
    const url = 'rest/auth/logout';
    return this.http.post(url, {})
      .do((res: Response) => {
        localStorage.removeItem('currentUser');
        console.log('hereee!');
        this.currentUser$.next(null);//will automatically trigger the logged-in state as well 
      });
  }
}

Komponentingizda

private desotryed$: Subject = new Subject();

ngOnInit() {
  this.authService.isSignedIn$
    .takeUntil(this.desotryed$)//to prevent memory leaks through a perpetual subscription
    .subscribe(isSignedIn => {
      this.isSignedIn = isSignedIn;
    });
}

ngOnDestroy() {
  this.desotryed$.next(true);
}

Since the RxJS5 docs are not including the BehaviorSubject yet, here is a link to the old docs: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md

2
qo'shib qo'ydi
Bu ish ishonaman (rahmat!), Lekin men javob berganim boshqa yondashuv bilan yugurdim. Logout() chaqiruvi bilan "$ event.preventDefault ()" ni qo'shish kabi ko'rinadi. Menga nima uchun u ishlaydi, deb ayta olasizmi?
qo'shib qo'ydi muallif Saket Mehta, manba

Mavzu bilan sizda shunday vaziyat mavjudki, emissiya faqatgina kelgusi abonentlar tomonidan emas, balki abonentlar tomonidan qabul qilinadi. Mening taxminimcha, bu sizning muammosiz bu erda - sizning hayotingizni osonlashtirishi uchun BehaviorSubject dan foydalanishingiz mumkin, u hozirgi qiymatini har qanday kelajakdagi abonentga qaytaradi, shuning uchun har qanday poyga shartlari haqida qayg'urishingiz kerak.

However: Strictly seen it will not be an event any more, but more of a state, which is what I would suggest to use anyways in your case - since with RxJS you can leverage the power of states over events.

@Injectable()
export class AuthService {

  public currentUser$: BehaviorSubject = new BehaviorSubject(null);//initial state is "null" => user is not logged in
  private isSignedIn$: Observable = currentUser$.map(user => Boolean(user)).share();

  constructor(private http: Http) {
    this.authEvents = new Subject();
  }

  login(email: string, password: string): Observable {
    const url = 'rest/auth/login';
    const body = {
      email: email,
      password: password
    };
    return this.http.post(url, body)
      .do((res: Response) => {
        localStorage.setItem('currentUser', JSON.stringify(res.json()));
        this.currentUser$.next(res.json());//will automatically trigger the logged-in state as well 
      });
  }

  logout(): Observable {
    const url = 'rest/auth/logout';
    return this.http.post(url, {})
      .do((res: Response) => {
        localStorage.removeItem('currentUser');
        console.log('hereee!');
        this.currentUser$.next(null);//will automatically trigger the logged-in state as well 
      });
  }
}

Komponentingizda

private desotryed$: Subject = new Subject();

ngOnInit() {
  this.authService.isSignedIn$
    .takeUntil(this.desotryed$)//to prevent memory leaks through a perpetual subscription
    .subscribe(isSignedIn => {
      this.isSignedIn = isSignedIn;
    });
}

ngOnDestroy() {
  this.desotryed$.next(true);
}

Since the RxJS5 docs are not including the BehaviorSubject yet, here is a link to the old docs: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md

2
qo'shib qo'ydi
Bu ish ishonaman (rahmat!), Lekin men javob berganim boshqa yondashuv bilan yugurdim. Logout() chaqiruvi bilan "$ event.preventDefault ()" ni qo'shish kabi ko'rinadi. Menga nima uchun u ishlaydi, deb ayta olasizmi?
qo'shib qo'ydi muallif Saket Mehta, manba

Mana, men uchun ishlagan narsa:

@Olsn taklif qilganidek, Mavzu ni BehaviorSubject ga o'zgartirdim.

Biroq, xatolik bor edi, aslida html-da.

  • Logout
  • 
    

    Men (click) hodisasida $ event.preventDefault() chaqirig'ini qo'shish va qo'shishga majbur bo'ldim. Agar kimdir buni menga tushuntirib bersa ham, nima uchun bunday bo'lsa, bu ajoyib bo'lardi!

    0
    qo'shib qo'ydi
    Buning sababi href = "#" <- buni olib tashlash va preventDefault shart emas - bu ilovaning "root" ga o'tishiga sabab bo'ladi. burchaklar routeriga to'siq bo'ladi
    qo'shib qo'ydi muallif olsn, manba
    Buni qilgan @olsn.
    qo'shib qo'ydi muallif Saket Mehta, manba

    Mana, men uchun ishlagan narsa:

    @Olsn taklif qilganidek, Mavzu ni BehaviorSubject ga o'zgartirdim.

    Biroq, xatolik bor edi, aslida html-da.

  • Logout
  • 
    

    Men (click) hodisasida $ event.preventDefault() chaqirig'ini qo'shish va qo'shishga majbur bo'ldim. Agar kimdir buni menga tushuntirib bersa ham, nima uchun bunday bo'lsa, bu ajoyib bo'lardi!

    0
    qo'shib qo'ydi
    Buning sababi href = "#" <- buni olib tashlash va preventDefault shart emas - bu ilovaning "root" ga o'tishiga sabab bo'ladi. burchaklar routeriga to'siq bo'ladi
    qo'shib qo'ydi muallif olsn, manba
    Buni qilgan @olsn.
    qo'shib qo'ydi muallif Saket Mehta, manba

    Mana, men uchun ishlagan narsa:

    @Olsn taklif qilganidek, Mavzu ni BehaviorSubject ga o'zgartirdim.

    Biroq, xatolik bor edi, aslida html-da.

  • Logout
  • 
    

    Men (click) hodisasida $ event.preventDefault() chaqirig'ini qo'shish va qo'shishga majbur bo'ldim. Agar kimdir buni menga tushuntirib bersa ham, nima uchun bunday bo'lsa, bu ajoyib bo'lardi!

    0
    qo'shib qo'ydi
    Buning sababi href = "#" <- buni olib tashlash va preventDefault shart emas - bu ilovaning "root" ga o'tishiga sabab bo'ladi. burchaklar routeriga to'siq bo'ladi
    qo'shib qo'ydi muallif olsn, manba
    Buni qilgan @olsn.
    qo'shib qo'ydi muallif Saket Mehta, manba
    Angular Uzbekistan
    Angular Uzbekistan
    107 ishtirokchilar

    Guruh Angular bo'yicha muloqot qilish uchun ochilgan Sizni qiziqtirsa: @nodejs_uz @react_uz @angular_uz @yiiframework_uz @js_uzb @typescript_uzb @vuejs_uz @ngTashkent @laravel_uz @uzdevgroup Ish o'rinlari @UzDev_jobs

    ngTashkent
    ngTashkent
    77 ishtirokchilar

    Правила просты: 1. Не хамить 2. Не хейтить 3. Реакт не нужен Ссылки: https://t.me/angular_ru - старший брат https://t.me/angular_uz - ангулар на узбекском @js_uzb @vuejs_uz @react_uz @nodejs_uz @yiiframework_uz @uzdevgroup @UzDev_Jobs @tasdev_talks