创建一个StatusCode和响应主体

时间:2018-08-03 14:18:54

标签: angular

我正在创建Angular应用程序,也在创建.Net Core API。

我想用post方法登录一个用户,但这是返回给我的:

  

选项https://localhost:44358/swagger/api/Employee 404()

     

无法加载https://localhost:44358/swagger/api/Employee:飞行前响应具有无效的HTTP状态代码404。

我的登录服务是:

export class LoginService {
auth : Login ;
constructor(
private http:HttpClient,
protected configService : ConfigService,
httpErrorHandler :HttpErrorHandlerService
) {  }
login(username: string, password: string) {
   return this.http.post<any>(`${this.configService.sendApiUrl()}Employee`, { username: username, password: password })
    .pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user.token) {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
        }

        return user;
    }));
}
logout() {
// remove user from local storage to log user out
    localStorage.removeItem('currentUser');
}

我的loginguard:

export class LoginGuard implements CanActivate {

constructor(private router: Router) { }


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
    }
}

我的login.component.ts

export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  submitted = false;
  returnUrl: string;
  constructor(
    private configService:ConfigService,
    private statusService : StatusService,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private loginService: LoginService,
    private alertService: AlertService) {  }


  ngOnInit() {
// this.getStatus();
this.loginForm = this.formBuilder.group({
              username: ['', Validators.required],
              password: ['', Validators.required]
          });
   
          // reset login status
          this.loginService.logout();
   
          // get return url from route parameters or default to '/'
          this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }


  get f() { 
    return this.loginForm.controls; 
  }


  onSubmit() {
  this.submitted = true;

  // stop here if form is invalid
  if (this.loginForm.invalid) {
      return;
  }

  this.loginService.login(this.f.username.value, this.f.password.value)
      .pipe(first())
      .subscribe(
          data => {
              this.router.navigate([this.returnUrl]);
          },
          error => {
              this.alertService.error(error);
          });
  }

我的错误拦截器:

    export class ErrorInterceptor implements HttpInterceptor {
    constructor(private loginService : LoginService ) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.loginService.logout();
                location.reload(true);
            }

            const error = err.error.message || err.statusText;
             return throwError(error);
        }))
    }
}

我的jwt拦截器:

    export class JwtInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
             request = request.clone({
                 setHeaders: {
                     Authorization: `Bearer ${currentUser.token}`
                 }
             });
        }
        return next.handle(request);
    }
}

我是Angular的新手,我真的不知道所有这些元素的作用。

我可以帮忙吗?

0 个答案:

没有答案