// app.config.ts
-import { FakeLoginService } from './fake-login.service';
...
export const appConfig: ApplicationConfig = {
providers: [
...
- // ==================================================
- // 👇 ❌ Remove it in the realworld application
- //
- { provide: LoginService, useClass: FakeLoginService },
+ { provide: LoginService, useClass: LoginService },
...
]
}
// proxy.config.js
const PROXY_CONFIG = {
...
+ '/api': {
+ target: 'http://my-api-url',
+ secure: false,
+ pathRewrite: {
+ '^/api': '', // 这样请求接口实际地址时,路径不会有 api 前缀
+ },
+ changeOrigin: true, // 如果对应接口地址不在 localhost 情况下
+ },
};
module.exports = PROXY_CONFIG;
ng-matero
已经默认支持代理,所以不需要修改 angular.json
文件。
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { map } from 'rxjs';
import { Menu } from '@core';
import { Token, User } from './interface';
@Injectable({
providedIn: 'root',
})
export class LoginService {
protected readonly http = inject(HttpClient);
login(username: string, password: string, rememberMe = false) {
return this.http.post<Token>('/api/auth/login', { username, password, rememberMe });
}
refresh(params: Record<string, any>) {
return this.http.post<Token>('/api/auth/refresh', params);
}
logout() {
return this.http.post<any>('/api/auth/logout', {});
}
me() {
return this.http.get<User>('/api/me');
}
menu() {
return this.http.get<{ menu: Menu[] }>('/api/me/menu').pipe(map(res => res.menu));
}
}
可以根据实际情况,将请求返回类型进行修改,比如接口带有信息的封装。
server {
listen 80;
server_name www.example.com;
...
location / {
# ng-matero 项目 web 服务器
proxy_pass http://localhost:port;
...
}
location /api {
# ng-matero 项目 api 服务器
rewrite ^/api/?(.*)$ /$1 break; # 如果真实路径没有 api 前缀
proxy_pass http://localhost:port;
...
}
}