【问题标题】:Angular 2+ subscribe not workingAngular 2+ 订阅不起作用
【发布时间】:2018-01-22 15:30:44
【问题描述】:

我的个人资料类有属性“lessonsID”。我在 my-offers.component 中订阅了 getProfile(),它成功返回了配置文件。问题是,当我在我的公告中单击“删除”时,my-offers.component 中的订阅配置文件不会更改,但是当我查看存储该配置文件的后端时,配置文件中的课程 ID 被删除。为什么订阅不起作用?如何解决?

我的offers.component.html

 <ul class="list">
    <li 
      class="list__item"
      *ngFor="let privateLesson of privateLessons"
    >         
      <app-my-announcement [privateLesson]="privateLesson"></app-my-announcement>
    </li>
  </ul>

my-offers.component.ts

export class MyOffersComponent implements OnInit {

myOffersId: string[];
privateLessons: PrivateLesson[] = [];

constructor(
  private _authService: AuthService,
  private _privateLessonsService: PrivateLessonsService
) { }

ngOnInit() {
  this._authService.getProfile().subscribe(
    profile => {
      this.myOffersId = profile.user.lessonsID;

      this.privateLessons = [];

      this.myOffersId.filter(offerID => {
        this._privateLessonsService.getPrivateLessonByID(offerID).subscribe(
          privateLesson => {
            this.privateLessons.push(privateLesson);
          }
        );
      });
    },
    err => {
      console.log(err);
      return false;
    }                  
  );
}

我的公告.components.html

<div class="announcement">
  <div class="announcement__data">
    <div class="data__title">
      {{ privateLesson.title }}    
    </div>
  </div>
  <div class="announcement__options">
    <ul class="options">
      <li 
        class="options__item"
        (click)="onPreviewClick(privateLesson._id)"
      >
        Podgląd
      </li>
      <li 
        class="options__item"
        (click)="onDeleteClick(privateLesson._id)"
      >
        Usuń
      </li>
    </ul>
  </div>
</div>

我的公告.component.ts

export class MyAnnouncementComponent implements OnInit {

  @Input() privateLesson: PrivateLesson;
  privateLessons: PrivateLesson[];

  constructor(
   private router: Router,
   private authService: AuthService,
   private _privateLessonsService: PrivateLessonsService
 ) { }

  onDeleteClick(id: string) {
    this._privateLessonsService.deletePrivateLessonByID(id).subscribe();
    this.authService.removeLesson(id);

  }

}

auth.service.ts

@Injectable()
export class AuthService {

 getProfile() {
    let headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get( 'http://localhost:3000/users/profile', { headers: headers } )
        .map( res => res.json() );
  }

}

【问题讨论】:

  • 您的删除订阅没有任何作用。 this._privateLessonsService.deletePrivateLessonByID(id).subscribe();?还有this.authService.removeLesson(id)应该怎么做?
  • 我在数据库中有两个数据集合,一个包含所有课程,另一个包含用户。 This.authService.removeLesson(id) 从实际登录用户的属性课程 ID 中删除 id。 This._privateLessonsService.deletePrivateLessonByID(id) 从存储所有课程的数据库中删除课程

标签: angular


【解决方案1】:

您需要像 here 解释的那样在“AuthService”上实现“Observable”

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AuthService {

    // Observable 
    private removeLessonObservable = new Subject<number>();
    // Observable number streams
    removeLessonSubscriber = this.removeLessonObservable.asObservable();
    // Event for notification from publisher to subscriber
    removeLessonEvent(value:number)
    {
        this.removeLessonObservable.next();
    }

    getProfile() 
    {
        let headers = new Headers();
        this.loadToken();
        headers.append('Authorization', this.authToken);
        headers.append('Content-Type', 'application/json');
        return this.http.get( 'http://localhost:3000/users/profile', 
            { headers: headers } ).map( res => res.json() );
    }

}

我的公告.component.ts

import { Component } from '@angular/core';
import { AuthService} from './auth.service';

export class MyAnnouncementComponent implements OnInit 
{

  @Input() privateLesson: PrivateLesson;
  privateLessons: PrivateLesson[];

  constructor(
     private router: Router,
     private authService: AuthService,
     private _privateLessonsService: PrivateLessonsService) { }

  onDeleteClick(id: string) 
  {
      this._privateLessonsService.deletePrivateLessonByID(id).subscribe();
      // Call the observable event
      this.authService.removeLessonEvent(id);    
  }
}

my-offers.component.ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { AuthService } from './auth.service';
    import { Subscription } from 'rxjs/Subscription';

    export class MyOffersComponent implements OnInit, OnDestroy {

    myOffersId: string[];
    privateLessons: PrivateLesson[] = [];

    // Subscriptions
      private authSubscription: Subscription;

    constructor(
      private _authService: AuthService,
      private _privateLessonsService: PrivateLessonsService
    ) { }



    ngOnInit() 
    {  
        // Subscription of the notifications
        this.authSubscription= this.authService.removeLessonSubscriber.subscribe(value =>
        {
            // Put the code for manage the notification here
            // 'value' contains the 'id'
            console.log(value);
        }

        this._authService.getProfile().subscribe(
            profile => {
              this.myOffersId = profile.user.lessonsID;

              this.privateLessons = [];

              this.myOffersId.filter(offerID => {
                this._privateLessonsService.getPrivateLessonByID(offerID).subscribe(
                  privateLesson => {
                    this.privateLessons.push(privateLesson);
                  }
                );
              });
            },
            err => {
              console.log(err);
              return false;
            }                  
          );
        }

    ngOnDestroy()
    {
      // Release subscription to avoid memory leaks when the component is destroyed
      this.authSubscription.unsubscribe();
    }
}

【讨论】:

  • 我已经更新了帖子,请查看 AuthService 的样子。
  • 我已经根据你的例子更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2016-10-09
  • 2019-12-04
  • 2020-12-13
  • 2018-08-14
  • 1970-01-01
相关资源
最近更新 更多