代码之家  ›  专栏  ›  技术社区  ›  Feroz Siddiqui

Angular-是否可以进行一个http调用,该调用通常需要一个组件10分钟,并通知另一个组件中的用户

  •  0
  • Feroz Siddiqui  · 技术社区  · 7 年前

    我在一个组件中有一个http调用,通常需要5-10分钟的处理时间。在这个http调用期间,我想确保所有其他路由器链接都按照它们的正常行为工作。当我从这个组件切换到另一个组件时,所有组件都将列出这个http调用处理的列表,一旦这个http处理完成,我想向用户显示一个通知,说明分析已经完成。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Henry    7 年前

    您可以从一个服务进行调用,并让应该在服务完成时得到通知的组件订阅该服务的可观察对象。

        2
  •  1
  •   marc_s    6 年前

    选择1

    将长http调用的执行移动到服务

    @Injectable()
    export class MyService {
    
      onNotificationRecieved: Subject<any>;
    
      constructor(private http: HttpClient) {
      }
    
      myLongHttpCall() {
        this.http.get('myurl').subscribe(result => {
          this.onNotificationRecieved.next(result);
        }, err => {
          //Handle error
        });
      }
    }
    

    并让活动组件监听结果

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnDestroy {
    
      private _unsubscribe: Subject<any>;
    
      constructor(private myService: MyService) {
        this._unsubscribe = new Subject();
    
        myService.onNotificationRecieved.pipe(takeUntil(this._unsubscribe)).subscribe(result => {
          //Show notification to user 
        });
      }
       ngOnDestroy(): void {
            // Unsubscribe from subscription
            this._unsubscribe.next();
            this._unsubscribe.complete();
        }
    
    }
    

    选择2 保留服务中的所有元素意味着您不必担心当前显示的是哪个ever组件

    @Injectable()
    export class MyService {
    
    
      constructor(private http: HttpClient, private snackBar: MatSnackBar) {
      }
    
      myLongHttpCall() {
        this.http.get('myurl').subscribe(result => {
          let config = new MatSnackBarConfig();
          this.snackBar.open('Your Notification Message', 'Dismiss', config);
        }, err => {
          //Handle fail
        });
      }
    }
    
    推荐文章