【发布时间】:2023-04-08 06:01:01
【问题描述】:
我已经将项目从 Angular 版本 5.1 迁移到 8,在此之后,一些使用 http 的 api 调用被更改为 httpClient,但是一旦我们启动项目,对服务层的第一次调用得到 404 未找到,调用没有到达服务层,下面是我的代码
const routes: Routes = [
{
path: '',
component: MasterComponent,
resolve: { "appUser": CheckAccessService },
children: [
{
matcher: ReadFinder,
loadChildren: () => import('app/Read-Finder/read-finder.module').then(m => m.ReadFinderModule),
canLoad: [CheckAccessService],
canActivateChild: [CheckAccessService]
},
----------------
--------------
]
},
{
path: '',
component: MasterPageComponent,
resolve: { "appUser": CheckAccessService },
children: [
{ path: 'NoAuthorityPage', component: NoAuthorityPageComponent },
{ path: '**', component: PageNotFound },
]
},
];
在 CheckAccessService 中,解析代码如下所示,
@Injectable()
export class CheckAccessService implements Resolve<UserInfo>, CanLoad, CanActivate, CanActivateChild {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<UserInfo> {
let url = window.location.pathname;
let _url = url.startsWith('/') ? url.substring(1) : url;
return new Observable<UserInfo>((subscriber: Subscriber<UserInfo>) => {
if (this.userInfo) {
subscriber.next(this.getCachedUserInfo());
subscriber.complete();
return;
}
this.navApiService.getUserInfo()
.subscribe(
user => {
this.storeUserInfo(user);
setTimeout(() => {
subscriber.next(user);
subscriber.complete();
});
},
err => {
this.storeUserInfo(null);
//clear session storage for unlogged users
window.sessionStorage.clear();
setTimeout(() => {
this.redirectOnFail(url, err.status === 403);
}, 3000);
}
)
});
}
}
在 resolve 方法中我们有一个 api 调用,这是从应用程序到服务器的第一次调用,它看起来像这样,
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ApiService {
constructor(public http: HttpClient) { }
getUserInfo(): Observable<UserInfoData> {
return this.http.get('/api/security/user-info')
.map(resp => <UserInfoData>resp)
.catch(err => {
return observableThrowError(err);
});
}
}
chrome中的错误是这样的,
【问题讨论】:
-
您是否检查过您的后端服务器是否在
localhost:4200上运行?还是别的什么?
标签: angular angular-ui-router xmlhttprequest httpclient