Angular 8-将API URL更改为本地服务器以进行登录验证

Angular 8-将API URL更改为本地服务器以进行登录验证,angular,jwt,local-storage,angular8,angular-local-storage,Angular,Jwt,Local Storage,Angular8,Angular Local Storage,我目前正在学习的教程是创建Angular 8应用程序,在该应用程序中,用户可以注册、创建帖子、查看全局帖子(如帖子)以及跟踪其他用户 本教程提供了一个运行于的实时API服务器,应用程序可以根据该服务器发出请求-这为应用程序提供了使用本教程的其他用户的帖子。以下是到github的链接,其中包含repo I克隆和定制: 但是,我想使用我自己的本地服务器(localStorage?)来测试我的应用程序,创建用户并自己发布。稍后,我将连接此API以与我的Java/Spring代码和PostgreSQL数

我目前正在学习的教程是创建Angular 8应用程序,在该应用程序中,用户可以注册、创建帖子、查看全局帖子(如帖子)以及跟踪其他用户

本教程提供了一个运行于的实时API服务器,应用程序可以根据该服务器发出请求-这为应用程序提供了使用本教程的其他用户的帖子。以下是到github的链接,其中包含repo I克隆和定制:

但是,我想使用我自己的本地服务器(localStorage?)来测试我的应用程序,创建用户并自己发布。稍后,我将连接此API以与我的Java/Spring代码和PostgreSQL数据库通信。

这就是我的
environment.ts
文件的外观:

export const environment = {
  production: false,
  api_url: 'https://conduit.productionready.io/api'
};
这就是我的
api.service.ts
文件的样子:

    import { Injectable } from '@angular/core';
    import { environment } from '../../../environments/environment';
    import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
    import { Observable ,  throwError } from 'rxjs';

    import { JwtService } from './jwt.service';
    import { catchError } from 'rxjs/operators';

    @Injectable()
    export class ApiService {
      constructor(
        private http: HttpClient,
        private jwtService: JwtService
      ) {}

      private formatErrors(error: any) {
        return  throwError(error.error);
      }

      get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
        return this.http.get(`${environment.api_url}${path}`, { params })
          .pipe(catchError(this.formatErrors));
      }

      put(path: string, body: Object = {}): Observable<any> {
        return this.http.put(
          `${environment.api_url}${path}`,
          JSON.stringify(body)
        ).pipe(catchError(this.formatErrors));
      }

      post(path: string, body: Object = {}): Observable<any> {
        return this.http.post(
          `${environment.api_url}${path}`,
          JSON.stringify(body)
        ).pipe(catchError(this.formatErrors));
      }

      delete(path): Observable<any> {
        return this.http.delete(
          `${environment.api_url}${path}`
        ).pipe(catchError(this.formatErrors));
      }
    }
README.md中的说明是:

如果要将API URL更改为本地服务器,只需编辑 src/environments/environment.ts并将api_url更改为本地 服务器的URL(即本地主机:3000/api)

但是当我这样做时(将
environment.ts中的
api\uurl:
更改为
)http://localhost:4200/api“
),并尝试创建一个帐户,页面不会做出反应,我在检查时在控制台中收到以下消息:

邮政404(未找到)


如何更改此设置,以便使用localStorage创建和存储用户?

我们有两个环境文件 1.environment.ts(development),其中8000是本地服务器的端口

  • environment.prod.ts(部署)http://*。:8080/AnalyticsServer-1.0,其中替换*为您的IP,8080为服务器端口(tomcat),AnalyticsServer-1.0为已部署war文件的名称

  • 端口
    4200
    用于运行angular应用程序的基本web服务器,同时
    ng SERVICE
    -ing。您目前是否有为您的API运行的web服务器?LocalStorage直接存在于浏览器中,它不是一个需要访问的服务器。您不会通过调用服务器将内容存储在浏览器的本地存储中。您只需转到
    localStorage.setItem(“itemname”,data)
    @JeremyThille,因此,假设如果我启动一个postgreSQL数据库,在端口8080的Tomcat服务器上运行它,然后设置api\u url:,它会将用户存储在我的postgres表中吗?我不知道,我从来没有这样做过。我从未使用过Tomcat或Postgre,但如果我将其转换为Mongo+节点,是的,我想soPostgresql不是一个像Mongo那样的无sql服务器,这意味着您需要执行一些sql语句来向其添加数据。如果8080上运行的服务器不是设计为接收数据并创建将数据输入数据库的SQL语句(如RESTAPI),那么它将无法工作。
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable ,  BehaviorSubject ,  ReplaySubject } from 'rxjs';
    
    import { ApiService } from './api.service';
    import { JwtService } from './jwt.service';
    import { User } from '../models';
    import { map ,  distinctUntilChanged } from 'rxjs/operators';
    
    
    @Injectable()
    export class UserService {
      private currentUserSubject = new BehaviorSubject<User>({} as User);
      public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged());
    
      private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
      public isAuthenticated = this.isAuthenticatedSubject.asObservable();
    
      constructor (
        private apiService: ApiService,
        private http: HttpClient,
        private jwtService: JwtService
      ) {}
    
      // Verify JWT in localstorage with server & load user's info.
      // This runs once on application startup.
      populate() {
        // If JWT detected, attempt to get & store user's info
        if (this.jwtService.getToken()) {
          this.apiService.get('/user')
          .subscribe(
            data => this.setAuth(data.user),
            err => this.purgeAuth()
          );
        } else {
          // Remove any potential remnants of previous auth states
          this.purgeAuth();
        }
      }
    
      setAuth(user: User) {
        // Save JWT sent from server in localstorage
        this.jwtService.saveToken(user.token);
        // Set current user data into observable
        this.currentUserSubject.next(user);
        // Set isAuthenticated to true
        this.isAuthenticatedSubject.next(true);
      }
    
      purgeAuth() {
        // Remove JWT from localstorage
        this.jwtService.destroyToken();
        // Set current user to an empty object
        this.currentUserSubject.next({} as User);
        // Set auth status to false
        this.isAuthenticatedSubject.next(false);
      }
    
      attemptAuth(type, credentials): Observable<User> {
        const route = (type === 'login') ? '/login' : '';
        return this.apiService.post('/users' + route, {user: credentials})
          .pipe(map(
          data => {
            this.setAuth(data.user);
            return data;
          }
        ));
      }
    
      getCurrentUser(): User {
        return this.currentUserSubject.value;
      }
    
      // Update the user on the server (email, pass, etc)
      update(user): Observable<User> {
        return this.apiService
        .put('/user', { user })
        .pipe(map(data => {
          // Update the currentUser observable
          this.currentUserSubject.next(data.user);
          return data.user;
        }));
      }
    
    }