角7手柄http请求(Angular 7 handle http request)

2019-10-28 09:55发布

我在得到一个简单的HTTP调用的工作问题。

我从angularjs来了,据我所知.then = .subscribe

因此,这里是我的问题,我不能使用.subscribe我的身份验证服务 ,而是在我的login.component.ts使用它,我想HTTP状态也。

auth.service

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的代码是什么样子。

auth.service

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');
    }

  });
};

Answer 1:

你是接近,但你应该做以下修改您的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,您可以通过返回观察到订阅它。 该认购方法处理回调nexterrorcomplete

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

编辑:如果您想阅读完整的响应体,您可以使用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', []))
  );


Answer 2:

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 
       }
       )


Answer 3:

subscribe()是不一样的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
});


文章来源: Angular 7 handle http request
标签: angular