代码之家  ›  专栏  ›  技术社区  ›  AbhiRam

http.get()方法在角度上不起作用

  •  1
  • AbhiRam  · 技术社区  · 6 年前

    我的目的是在Angular中使用REST Web服务,现在我正在进行一些测试。下面的代码不工作,将进入错误块。你能帮我找出问题所在吗?事先谢谢。

     interface UserResponse {
         login: string;
         bio: string;
         company: string;
       }
    
        constructor(public http: HttpClient) {
            this.http.get<UserResponse>('https://api.github.com/users/seeschweiler')
            .pipe( tap(heroes =>{
                 alert()
                 }),
              catchError(this.handleError('getHeroes', []))
            );
          }
    
          private handleError<T> (operation = 'operation', result?: T) {
               alert()
          return (error: any): Observable<T> => {
            // TODO: send the error to remote logging infrastructure
            console.error(error); // log to console instead
    
            // TODO: better job of transforming error for user consumption
            console.log(`${operation} failed: ${error.message}`);
    
            // Let the app keep running by returning an empty result.
            return of(result as T);
          };
        }
    
    3 回复  |  直到 6 年前
        1
  •  0
  •   Antoniossss    6 年前

    HttpClient#get() 提供所谓的“冷观测”。这意味着,它不会执行引擎盖下的任何操作,直到有一个可观测的订户。此外,多个订阅(默认情况下)将导致进行多个请求(除非您以特定的“共享”方式进行管道传输)

    所以:

        this.http.get<UserResponse>('https://api.github.com/users/seeschweiler')
        .pipe( tap(heroes =>{
             alert()
             }),
          catchError(this.handleError('getHeroes', []))
        ).subscribe(result=>console.log(result));
    

    会提出你的要求。

    请仔细阅读并理解你正在经历的教程(英雄之旅),因为这些方面在那里有合理的细节解释。

        2
  •  0
  •   Amit Kumar Saha    6 年前

    当它返回Observable时,您需要订阅该值。这是解决方案和结果。

    this.http.get<any>('https://api.github.com/users/seeschweiler').subscribe( x => console.log(x));

    控制台中的结果 Result :

        3
  •  0
  •   Oleksandr Martyniuk    6 年前

    您需要订阅Observable来启动它:

    ....
    constructor(public http: HttpClient) {
        this.http.get<UserResponse>('https://api.github.com/users/seeschweiler')
        .catch(this.handleError('getHeroes', [])))
        .subscribe(response => console.log(response));
      }
      ....
    

    或者,如果你想的话,你仍然可以使用pipe,但是你仍然需要订阅

        constructor(public http: HttpClient) {
        this.http.get<UserResponse>('https://api.github.com/users/seeschweiler')
        .pipe(
            tap(response => { 
                console.log(response); 
                /* process your data */ 
                return response;}),
            catchError(this.handleError('getHeroes', [])),
            )
        .subscribe(processingResult => /* handle processed response */);
      }