我想知道使用哪一个来构建模拟Web服务来测试Angular程序?
这是我的代码:
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)
logIn(username: string, password: string) {
const url = 'http://server.com/index.php';
const body = JSON.stringify({username: username,
password: password});
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json; charset=utf-8');
this.http.post(url, body, {headers: headers}).subscribe(
(data) => {
console.log(data);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Client-side error occured.');
} else {
console.log('Server-side error occured.');
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
在这里网络调试:
Request Method:POST
Status Code:200 OK
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:46
Content-Type:text/plain …Run Code Online (Sandbox Code Playgroud) 我一直在寻找一种方式来传递查询paramters与新API调用HttpClientModule的HttpClient,还没有找到一个解决方案.使用旧Http模块,您可以编写类似这样的内容.
getNamespaceLogs(logNamespace) {
// Setup log namespace query parameter
let params = new URLSearchParams();
params.set('logNamespace', logNamespace);
this._Http.get(`${API_URL}/api/v1/data/logs`, { search: params })
}
Run Code Online (Sandbox Code Playgroud)
这将导致对以下URL的API调用:
localhost:3001/api/v1/data/logs?logNamespace=somelogsnamespace
但是,新HttpClient get()方法没有search属性,所以我想知道在哪里传递查询参数?
我有一个如下所示的数据服务:
@Injectable()
export class DataService {
baseUrl = 'http://localhost'
constructor(
private httpClient: HttpClient) {
}
get(url, params): Promise<Object> {
return this.sendRequest(this.baseUrl + url, 'get', null, params)
.map((res) => {
return res as Object
})
.toPromise();
}
post(url, body): Promise<Object> {
return this.sendRequest(this.baseUrl + url, 'post', body)
.map((res) => {
return res as Object
})
.toPromise();
}
patch(url, body): Promise<Object> {
return this.sendRequest(this.baseUrl + url, 'patch', body)
.map((res) => {
return res as Object
})
.toPromise();
}
sendRequest(url, type, body, params …Run Code Online (Sandbox Code Playgroud) 我尝试将Angular 4的POST请求发送到我的Laravel后端.
我的LoginService有这个方法:
login(email: string, password: string) {
return this.http.post(`http://10.0.1.19/login`, { email, password })
}
Run Code Online (Sandbox Code Playgroud)
我在LoginComponent中订阅了这个方法:
.subscribe(
(response: any) => {
console.log(response)
location.reload()
},
(error: any) => {
console.log(error)
})
Run Code Online (Sandbox Code Playgroud)
这是我的Laravel后端方法:
...
if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
return response('Success', 200);
}
return response('Unauthorized', 401);
Run Code Online (Sandbox Code Playgroud)
我的Chrome开发工具说我的请求是成功的200状态代码.但我的Angular代码触发了error阻止并给了我这条消息:
解析http://10.0.1.19/api/login期间的Http失败
如果我从后端返回一个空数组,它可以工作......所以Angular试图将我的响应解析为JSON?我怎么能禁用它?
我没有在文档中找到为所有http请求设置基本API URL的方法.是否可以使用Angular HttpClient?
我正在使用CLI启动一个新的角度项目,并且我遇到了HttpClient错误的无提供程序.
我已经添加HttpClientModule到我的模块导入,这似乎是这种情况下的常见罪魁祸首.除此之外没有找到很多在线,所以我不确定问题是什么.
我的app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
和我的服务
@Injectable()
export class FlexSearchService {
constructor(private http: HttpClient) {}
getSavedSearchResult(index: string, queryName: string, query: string ): Observable<any> {
const url = `${environment.flexUrl}/${index}/search`;
const item = new SearchQuery({queryName: queryName, variables: {q: query}});
return this.http.post(url, item);
}
}
Run Code Online (Sandbox Code Playgroud)
和ng版本提供以下输出
@angular/cli: 1.4.2
node: 6.9.4
os: darwin x64
@angular/animations: 4.4.4
@angular/common: 4.4.4
@angular/compiler: 4.4.4
@angular/core: 4.4.4 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用角度为2的HttpClient通过REST获取数据.我在这里按照角度教程https://angular.io/tutorial/toh-pt6并在英雄和HTTP部分下你会看到这段代码用于通过http获取英雄数据.
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
以下是我在我的应用程序中编写的类似版本
fetch(startIndex: number, limit: number): Promise<Order[]> {
let url = this.baseUrl + "&startIndex=" + startIndex + "&limit=" + limit;
return this.http.get(url)
.toPromise()
.then(response => response.json().results as Order[])
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用InteliJ Idea,并且在调用response.json()时有一条红线,即使我尝试使用ng build构建,我也会收到错误.
属性'json'在'Object'类型上不存在.
您可能会注意到,而不是json().data我json().results.这是因为根据教程,服务器响应了一个具有data字段的对象,但我自己的服务器使用具有results字段的对象进行响应.如果您向下滚动教程,您会看到这一点.
请注意服务器返回的数据的形状.此特定的内存中Web API示例返回具有data属性的对象.您的API可能会返回其他内容.调整代码以匹配您的Web API.
为了解决这个问题,我试过这样的事情
(response: Response) => response.json().results as Order[]
Run Code Online (Sandbox Code Playgroud)
当我这样做时,.json()方法已被解决,但另一个错误弹出
Promise类型不存在属性结果
我尝试通过定义一个接口来修复它
interface OrderResponse {
orders: Order[]; …Run Code Online (Sandbox Code Playgroud) 我们的项目正在迁移到Angular4,并@angular/common/http Httpclient用作默认的网络工具.但我发现body删除功能中没有参数.如何添加正文以删除功能?谢谢.
我正在从HttpServer升级到HttpClientService,作为其中的一部分,我必须将标题从Headers切换到HttpHeaders.但是由于某些原因,我的自定义标题不再被追加.我需要更新什么才能添加标题?
private getHeaders(headers?: HttpHeaders): HttpHeaders {
if (!headers) {
headers = new HttpHeaders();
}
headers.delete('authorization');
const token: any = this.storageService.getItem('token');
if (token) {
headers.append('Authorization', 'Bearer ' + token);
}
const user: User = this.storageService.getObject('user');
if (user && Object.keys(user).length) {
headers.append('X-Session-ID', user.uuid);
headers.append('X-Correlation-ID', this.uuidService.generateUuid());
}
return headers;
}
Run Code Online (Sandbox Code Playgroud)
该方法返回一个httpHeader,但它是空的.