Angular 解析器中的 HttpClient 问题

Angular HttpClient issue in resolver

在启用 AOT 编译的情况下使用 Angular 2(Angular 通用),在自定义解析器中出现错误..

Uncaught (in promise): Error Error: Uncaught (in promise): Error

问题似乎与我 return HttpClient 调用的结果(这只是一个简单的数字)有关。

如果我关闭服务器端渲染,一切正常。以下是代码的摘录。

constructor(private httpClient : HttpClient)
{

}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): number | Observable<number> | Promise<number> {

    try{
        return this.httpClient.get<number>(`/api/something/getnumber`);
    }catch(e){
         console.log(e);              
    }
    return -1;
}

这是服务器端渲染中的一个基本问题吗?还是我只是缺少启用服务器端渲染所需的一些关键配置?

像这样尝试下面的代码是我的示例:

@Injectable()
export class HomeActionResolve implements Resolve<any> {

    constructor(private http: Http) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        try {
            return this.http.get('assets/json/sample.json');
        } catch (e) {
            console.log(e);
        }
        return -1;
    }
}

export const HomeRoute: Routes = [
    {
        path: '',
        component: HomeComponent,
        resolve: {
            'pagingParams': HomeActionResolve
        }
    }
];

这与您因此获得非 json 数据这一事实有关。将 {responseType: 'text'} 添加到您的呼叫中以指定此项。

return this.httpClient.get<number>(`/api/something/getnumber`, {responseType: 'text'});

另请参阅文档 Requesting non-JSON data

Not all APIs return JSON data. Suppose you want to read a text file on the server. You have to tell HttpClient that you expect a textual response: