Angular 7处理http请求

时间:2019-03-06 01:57:11

标签: angular

我在获取一个简单的http调用上班时遇到问题。

我来自angularjs和AFAIK .then = .subscribe

所以这是我的问题,我不能在我的 auth-service 中使用.subscribe,而是在我的 login.component.ts 中使用它,还要获取 Http状态

身份验证服务

const httpOptions = {
   headers: new HttpHeaders({
       'Content-Type': 'application/json'
    })
}

export class AuthService {
 constructor(private http: HttpClient) { }
 mainUrl = 'http://localhost:4000/api/v1';
 signIn(user: User) { // this is working fine, BUT I want to use .subscribe in login component
    const url = `${this.mainUrl}/sign_in`;
    return this.http.post<any>(url, user, httpOptions)
    .subscribe(
    (data) => {
      console.log(data); // I want to get the 200 status not only the jwt token
      return data;
    },
    (error) => console.log(error)
  )
 }
}

login.component.ts

this.authService.signIn(userData); // how to use .subscribe here ? 

更新:

这是我的angularjs代码的样子。

身份验证服务

function signIn(data) {
        return $http.post(url + '/api/v1/sign_in_2', data)
            .then(success)
            .catch(fail);

        function success(response) {
            setToken(response.data.jwt);
            return response;
        }

        function fail(e) {
            return e;
        }
    }

login.ctrl

vm.doLogin = function (userData) {
  vm.spinner = true;
  elixirAuthServices.signIn(userData).then(function (data) {

    if (data.status === 200 || data.status === 201) {
      elixirAuthServices.getUser().then(function (data) {
        vm.user_id = data.data.id;
        redirect();
      });
    } else {
      vm.authenticateErr = true;
      vm.spinner = false;
      logger.info('Username or Password is incorrect');
    }

  });
};

3 个答案:

答案 0 :(得分:5)

您很接近,但是您应该对service.ts进行以下修改。如果您打算使用它们,请不要忘记导入所需的RxJS运算符,例如管道和地图。

import { catchError, map, tap } from 'rxjs/operators';

signIn(user: User) {
  const url = `${this.mainUrl}/sign_in`;
  return this.http.post<any>(url, user, httpOptions).pipe(
    // additional operations before returning observable
    //map(data => ....), 
    //catchError(this.handleError('signIn', []))
  );
 }

在component.ts上,您可以将subscribing的可观察对象返回给它。 subscription方法处理nexterrorcomplete的回调。

this.authService.signIn(userData).subscribe(success => {
   // next
   // .. handle successful response (status code 200)
}, error => {
   // handle errors
   console.log(error.status)
}, () => {
   // complete 
})

编辑:如果要阅读FULL响应正文,可以使用observe选项

this.http.post<any>(url, user, { observe: 'response' }).pipe(
    //additional operations before returning observable
    //tap(response => console.log(response.status)
    //map(response => response.body), 
    //catchError(this.handleError('signIn', []))
  );

答案 1 :(得分:1)

subscribe()与Promise中的then()方法不同。您只需要返回http.post()对象的结果Observable,然后在组件中订阅可观察对象。

如果要捕获错误,请在服务中链接catch()方法。

auth.service.ts

signIn(user: User) { 
  const url = `${this.mainUrl}/sign_in`;
  return this.http.post<any>(url, user, httpOptions)
    .pipe(
      tap(val => console.log(val)), // do what you want with val
      catchError(error => console.log(error))
    )
}

login.component.ts

this.authService.signIn.subscribe(userData => {
  // do what did in login.ctrl
});

答案 2 :(得分:1)

可观察到的RxJs

    signIn(user){
        return this.httpClient.post<any>(url, user, option)
            .pipe(
            map(res => res),
            retry(1),
            catchError(err => throwError(err))
            )
    }

然后您可以在LoginComponent上订阅响应并捕获错误

   this.authService.signIn(userData).subscribe(res => {
       // do something here
       }, err => {
       // catch err here 
       }
       )