刚发现BrowserModule和HttpClientModule没有实现NgModule接口.有人可以解释一下原因吗?
更新:我试图解决的实际问题是提取导入部分以分离我可以根据特定规则创建的数组.所以我的想法是指定这个数组的类型.我不想放在any这里:
const importedModules: any[] = [
BrowserModule,
HttpClientModule,
FormsModule,
SharedModule,
...
];
if (!environment.production) {
importedModules.push(StoreDevtoolsModule.instrument());
}
@NgModule({
//...
imports: importedModules,
//...
})
Run Code Online (Sandbox Code Playgroud) 我有一个客户端具有日期类型属性的对象.当我尝试将对象发送HttpClient.post到服务器时,属性的值将更改为UTC时区.
客户端值为2017年11月26日星期日00:00:00 GMT + 0300(土耳其标准时间),但当它进入服务器时,更改为:25.11.2017 21:00:00
我该怎么控制呢?
这是我的班级.
export interface IBill {
BillID : number;
SubscriptionID:number;
SiteID : number;
SubscriptionName: string;
Amount: number;
Date: Date;
PaymentDeadline: Date;
Virtual: boolean;
Portioned: boolean;
Issuanced: boolean;
FinancialTransactionComment : string;}
Run Code Online (Sandbox Code Playgroud)
我在填写ng-form时创建了一个对象,然后调用Http.post:
let bill = this.formData;
this.http.post(this.configuration.ServerWithApiUrl + url, bill , { headers: headers, withCredentials: true, observe: "response", responseType: 'text' })
.map((response) => {
return this.parseResponse(response);
}).catch(
(err) =>
this.handleError(err));
Run Code Online (Sandbox Code Playgroud) 我正在尝试实现401响应的catch,并尝试在令牌刷新后基于Angular 4 Interceptor重试请求获取刷新令牌 .我试图实现同样的事情,但我从来没有能够重试该请求,我真的不确定这是否是应用刷新令牌策略的最佳方法.这是我的代码:
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
public authService;
refreshTokenInProgress = false;
tokenRefreshedSource = new Subject();
tokenRefreshed$ = this.tokenRefreshedSource.asObservable();
constructor(private router: Router, private injector: Injector) { }
authenticateRequest(req: HttpRequest<any>) {
const token = this.authService.getToken();
if (token != null) {
return req.clone({
headers: req.headers.set('Authorization', `Bearer ${token.access_token}`)
});
}
else {
return null;
}
}
refreshToken() {
if (this.refreshTokenInProgress) {
return new Observable(observer => {
this.tokenRefreshed$.subscribe(() => {
observer.next();
observer.complete();
});
});
} else …Run Code Online (Sandbox Code Playgroud) 我是角度5的新手.如何编写一个通用函数来为角度为5的每个HTTP请求显示微调器.请帮我实现这个.
angular-http angular-http-interceptors angular angular-httpclient
在我的 Angular 应用程序中,我有一个上传页面。上传由服务处理并由 NGRX 效果触发。
// service
public upload(file: File): any {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
// create a http-post request and pass the form
// tell it to report the upload progress
const request = new HttpRequest('POST', url, formData, {
reportProgress: true
});
return this.httpClient.request(request);}
// Effect
@Effect({ dispatch: false })
uploadFile = this.actions
.ofType(ActionTypes.UploadFile)
.map(toPayload)
.switchMap(file =>
this.service.upload(file).map(event => {
if (event.type === HttpEventType.UploadProgress) {
// calculate the progress percentage
const percentDone = …Run Code Online (Sandbox Code Playgroud) 如果我有如下代码:
const d: any = {};
return this.http.post(url, body, httpOptions).map(data => {
return d;
}, error => {
console.error('error');
})
.catch((err, d$) => {
return Observable.of(d);
});
Run Code Online (Sandbox Code Playgroud)
以及是否存在任何类型的错误,即POST请求失败,.map()成功回调中的某些错误或任何其他类型的错误。
这两个错误处理程序中的哪一个将在.map()或回调上被调用.catch()?是否取决于可能发生的错误的类型?
.map()是否总是因为.catch()操作员的存在而跳过错误回调?
我在 app.module.ts 中实例化 MyService,并在我的代码中提供它。
但是,我希望 MyService 使用 httpClient,并且我无法以角度惯用方式实例化 httpClient 以作为参数传递给 MyService。我不确定在 MyService 中访问 httpClient 的正确方法是什么。
我考虑过直接实例化 httpClient ,然后将其作为参数传递给我的服务。然而,这似乎造成了循环依赖。我也尝试过弄乱注入器,但显然 Angular 团队特别建议不要这样做。我强烈地觉得我错过了一些简单的东西。
应用程序模块.ts
imports: [
...
httpClientModule
...
],
function MainServiceFactory() {
return new MyService();
}
...
providers: [{
provide: MyService,
useFactory: MainServiceFactory
}],
...
Run Code Online (Sandbox Code Playgroud)
MyService.ts
...
constructor(private http : HttpClient) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果没有实例化并作为 httpClient 的参数传递:我自然会收到“app.module.ts 中的错误,预期 1 个参数”!通过实例化,我打破了角度建议。
编辑: 我忽略了指定我确实导入了 httpClientModule
在我这里,UserService我有一个用户Observable对象,该对象保存已UserModel登录用户ngOnInit()的身份。为进行测试,我在登录过程中实现了该对象:
this.userService.authenticate('###', '###')
.subscribe(res => console.log('authenticated'));
Run Code Online (Sandbox Code Playgroud)
private userSource = new BehaviorSubject<UserModel>(null);
public user = this.userSource.asObservable();
Run Code Online (Sandbox Code Playgroud)
我的UserModel提供了一个称为authKey的属性,用于API身份验证。
在我ProjectService我想要做的API请求; 为此,UserModel必须存储在中的api密钥。只可能订阅用户属性,但是我读到有关避免在服务内部进行订阅的信息。
题
如何将该订阅与管道/映射连接起来?我的方法是以下代码;但这感觉像是不好的代码。
suggest(term: string): Observable<ProjectModel[]> {
return this.userSrv.user.pipe(
mergeMap((user: UserModel) => {
const options = {params: {'access-token': user.accessToken}};
return this.http.get<ProjectModel[]>(this.conf.url, options).pipe(
map(response => {
// mapping the projects ...
return projects;
})
);
})
);
}
Run Code Online (Sandbox Code Playgroud) 当我使用 Angular HttpClient 发出 GET 请求时,我会得到一个可观察的数据并在 RxJS 运算符 mergeMap 中处理它。
现在,一次又一次地抛出 404,我想抓住它。最后,浏览器控制台中不应出现任何错误消息,并且应使用流的下一个值来处理管道。
有这种可能吗?我没有用catchError()来管理它。
这是我的代码的简化版本:
...
this.service1.getSomeStuff().pipe(
mergeMap((someStuff) => {
return from(stuff);
}),
mergeMap((stuff) => {
return this.service2.getMoreStuff(stuff.id); // Here I need some error handling, if 404 occurs
}),
mergeMap((things) => {
return from(things).pipe(
mergeMap((thing) => {
if (allLocations.some(x => x.id === metaData.id)) {
return this.service2.getMore(thing.id, thing.type, thing.img_ref);
}
}),
map((thing) => {
...
Run Code Online (Sandbox Code Playgroud)
更新:添加了 catchError() 方法
我尝试了这种方式,但是没有检测到错误,并且下一个 mergeMap 不起作用(IDE 不再识别thing.id、thing.type、thing.img_ref等参数):
...
this.service1.getSomeStuff().pipe(
mergeMap((someStuff) => {
return from(stuff);
}), …Run Code Online (Sandbox Code Playgroud) 我面临 RxJS 的forkJoin运算符和 http 请求被 chrome 取消的问题。
我有一个名为 的可观察对象数组(即 http 请求)validationSupportBatch$。
我按如下方式使用该数组:
this.subscription.add(
forkJoin<T>(validationSupportBatch$)
.pipe(mergeMap(() => this.getByStandardActivityCode()))
.subscribe((svs: T[]) => {
this.validationSupports = svs;
this.notificationService.success('SVS.SAVE.success');
},
error => this.notificationService.error('SVS.SAVE.failure')
)
);
Run Code Online (Sandbox Code Playgroud)
不幸的是,这些请求被 Chrome 取消了(请参见下面的屏幕截图,了解一批 3 个 http 请求)。
有人可以帮忙吗?
编辑:
以下是请求标头:
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer XXX
Content-Type: application/json
Origin: https://localhost:4200
Referer: https://localhost:4200/validation/applied/activity/HHN-KADJAR-A0000020/standard-validation-support?planId=HHN-KADJAR-I001
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
x-validation-context: APPLIED
x-validation-project-family: HHN …Run Code Online (Sandbox Code Playgroud) angular ×9
rxjs ×4
observable ×2
angular-http ×1
angular5 ×1
date ×1
interceptor ×1
jwt ×1
ngrx ×1
ngrx-effects ×1
rxjs5 ×1
subscription ×1