我成功完成了angular2"英雄之旅"入门教程.然后我基于symfony3,FosRestBundle和BazingaHateoasBundle构建一个api作为后端.现在几乎所有东西都可以工作,但是在创建新项目时,我无法从响应中获取"Location"标头来加载新创建的Item.
这是我的英雄服务:
import {Injectable} from "angular2/core";
import {Hero} from "./hero";
import {Http, Headers, RequestOptions, Response} from "angular2/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";
@Injectable()
export class HeroService {
constructor(private _http:Http) {
}
private _apiUrl = 'http://tour-of-heros.loc/app_dev.php/api'; // Base URL
private _heroesUrl = this._apiUrl + '/heroes'; // URL to the hero api
getHeroes() {
return this._http.get(this._heroesUrl)
.map(res => <Hero[]> res.json()._embedded.items)
.do(data => console.log(data)) // eyeball results in the console
.catch(this.handleError);
}
addHero(name:string):Observable<Hero> {
let body = JSON.stringify({name});
let headers = new …Run Code Online (Sandbox Code Playgroud) 我正在使用Angular 2 HTTP库,它返回一个observable.我想在某些错误状态/代码上实现重试.
我有一个问题,如果错误不是429,Observable.of(error)则在错误情况下执行以重试,但是当所有2次重试失败时,流程的执行将转到成功块而不是catch块.
如何在所有重试中执行流程以捕获块失败?
return this.http.get(url,options)
.retryWhen((errors) => {
return errors
.mergeMap((error) => (error.status === 429) ? Observable.throw(error) : Observable.of(error))
.take(2);
})
.toPromise()
.then((res:Response) => console.log('In Success Block'))
.catch((res) => this.handleError(res));
Run Code Online (Sandbox Code Playgroud)
它会解决我的问题吗?
return this.http
.post(url, JSON.stringify(body), requestOptions).retryWhen((errors) => {
return errors
.mergeMap((error) => (error.status === 404) ? Observable.throw(error) : Observable.of(error))
.take(2);
}).map((res:Response) =>{
if (res.status === 200)
return res;
else
return Observable.throw(res);
})
.toPromise();
Run Code Online (Sandbox Code Playgroud) 我在HTTP超时发布自定义错误消息时遇到问题.
这是一个简单的例子:
return this._http.get(url).timeout(5000, new Error("Error message"));
Run Code Online (Sandbox Code Playgroud)
我看到每个人都使用新的错误("错误消息"),但我收到错误:
错误函数需要类型Scheduler.我收到此错误:"错误"类型的参数不能分配给"调度程序"类型的参数."错误"类型中缺少属性"SchedulerAction"
我已经升级,从角4.2应用5,但更改后Http到HttpClient了对POST请求的错误:
错误,服务器响应状态为415(不支持的媒体类型)
在app.module我已经导入HttpClientModule:
import { HttpClientModule } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)
旧代码:
post(url: string, model: any): Observable<any> {
let body = JSON.stringify(model);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(url, body, options)
.map((response: Response) => <any>response.json())
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
新代码:
put(url: string, id: number, model: any): Observable<any> {
let body = JSON.stringify(model);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options: any = new …Run Code Online (Sandbox Code Playgroud) 我正在从 angular2 应用程序调用外部 API,该应用程序以分页形式提供数据。响应看起来像这样
{
next: "next_url",
results: []
}
Run Code Online (Sandbox Code Playgroud)
我可以使用 Rxjs 或 Angular2 的内置 Http 类(它返回一个 observable)来连接下一个 url 的结果,直到
{
next: null,
results: []
}
Run Code Online (Sandbox Code Playgroud)
我觉得我需要使用 concatMap 运算符,但我还没有弄清楚语法,因为我是 Reactive Extentions 的新手。
我在LoginComponent中有登录功能:
login() {
this.loading = true;
this.subscription = this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
this.em.changeNav(1);
this.loading = false;
this.Auth.setToken(result);
this.router.navigate(['/code']);
this.subscription.unsubscribe();
},
err => {
this.error = JSON.parse(err._body).error;
this.loading = false;
});
}
Run Code Online (Sandbox Code Playgroud)
this.authenticationService.login 是向api发送http请求的服务...
这是测试:
it('should login', fakeAsync(() => {
spyOn(component, 'login');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
//CHECK IF LOGIN FUNCTION CALLED
fixture.whenStable().then(() => {
expect(component.login).toHaveBeenCalled();
})
}));
Run Code Online (Sandbox Code Playgroud)
如何this.authenticationService.login在订阅方法中模拟服务和断言?
编辑
测试:
import { async, ComponentFixture, TestBed, fakeAsync, tick, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; …Run Code Online (Sandbox Code Playgroud) 我有一系列通过循环遍历小工具的Http调用.有没有办法中止所有请求
for (let gadget of gadgets) {
this.userService.getGadgetsData(gadget.Id, gadget.Name).subscribe(gadgetsData => {
});
}
Run Code Online (Sandbox Code Playgroud)
我在component.service.ts中的服务代码
@Injectable()
export class UserService {
constructor(public _http: Http) { }
getGadgetsData() {
return this._http.get(this._dashboards, { headers: this.getHeaders() })
.map((res: Response) => res.json());
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用observable
服务
getMembers(): Observable<any[]> {
return this._http.get('http://localhost/membership/main/getUsers')
.map(response => response.json() );
}
Run Code Online (Sandbox Code Playgroud)
零件
members$: Observable<any[]>;
ngOnInit() {
this.members$ = this._membersService.getMembers()
}
Run Code Online (Sandbox Code Playgroud)
要求
-getUsers
-getUsers
Run Code Online (Sandbox Code Playgroud)
两者都返回相同的JSON数据
每次加载页面时,它都会返回重复的请求.这不是关于冷热要求.因为两个请求都返回相同的响应.但是当我删除了observable时,一切都还可以.只有一个请求
这有效:
this.http.get('/doesntexist1')
.finally(() => console.log('finally1'))
.subscribe(() => { });
Run Code Online (Sandbox Code Playgroud)
但这不是:
const obs = this.http.get('/doesntexist2');
obs.finally(() => console.log('finally2'))
obs.subscribe(() => { });
Run Code Online (Sandbox Code Playgroud)
两个URL都产生404.
我跑两个,我只看到控制台中显示"finally1",任何想法为什么?
我的有角4.3.2代码正在调用我的后端服务,该服务需要2-4分钟才能返回。仅使用默认this.http.get代码,我看到默认超时在2分钟后开始。但是,当我尝试将超时时间设置为超过2分钟时,它将失败,因为它将永远不会使超时时间超过2分钟。
我尝试使用100、100000(1.7m)和114000(1.9m),并且在这些值下超时的工作方式是正确的。但是当我尝试126000(2.1m),180000(3m)和1800000(30m)时,我再次看到它在2分钟后超时。
this.http.get('myUrl')
.timeout(126000)
.map((res: Response) => this.convertResponse(res));
Run Code Online (Sandbox Code Playgroud)
我也尝试了一下,.timeoutWith(126000, Observable.throw(new Error("Timed out")))但无济于事。
angular2-http ×10
angular ×9
rxjs ×4
observable ×2
cors ×1
hateoas ×1
rxjs5 ×1
symfony ×1
typescript ×1
unit-testing ×1