我有一个带有路由和解析防护的 Angular 应用程序。解析守卫是异步的,并返回一个从返回的可观察量HttpClient.post- 问题是,AJAX 请求完成但可观察量没有完成,因此解析器永远不会完成其工作,并且页面永远不会显示。然而,当我通过管道传输结果时,take(1)它确实完成并且工作正常。我的问题是为什么?HttpClient.postAJAX 请求返回 ok ( ) 后不应该完成吗200 OK?
这是我的解析器的代码:
@Injectable()
export class MyDataResolver implements Resolve<MyData> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
: MyData | Observable<MyData> | Promise<MyData> {
return this.svc.getData().pipe(take(1)); // <-- Why is take(1) necessary here??
}
constructor(private svc: MyService) { }
}
Run Code Online (Sandbox Code Playgroud)
这是调用的服务方法post:
import { HttpClient } from '@angular/common/http';
export class MyService {
constructor(private http: HttpClient) {}
getData(): Observable<MyData> {
return this.http.post('/api/data'), {}).pipe(
map((resp: { data: …Run Code Online (Sandbox Code Playgroud) 我定义了一个简单的select变量绑定,如下所示:
<select id="client" name="client" [(ngModel)]="order.clientId">
<option *ngFor="let client of clients" [value]="client.id">
{{ client.name }}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这clients是一个带有数值的简单类id:
<select id="client" name="client" [(ngModel)]="order.clientId">
<option *ngFor="let client of clients" [value]="client.id">
{{ client.name }}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
所以我希望该值是一个数字,而不是一个字符串。并且order.clientId也被定义为一个数字。但是,当我像这样order通过HttpClientpost 调用传递对象时,它将值编码为字符串:
export class NameAndId {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么它不显示为数值?
我在网上找到的所有例子都是这样的:
createArticle(article: Article): Observable<Article> {
return this.http.post<Article>(this.url, article);
}
Run Code Online (Sandbox Code Playgroud)
因此他们假设 Web API 的响应包含 Article。如何编写上面的内容以便将文章发布到 Web API 并且响应是字符串?
我正在使用 HttpClient 创建 POST 请求并将 Observable 返回给调用者。当调用者订阅并尝试捕获错误时,错误是一个字符串,而不是文档中通常看到的预期 HttpErrorResponse。

我尝试使用带有 catchError 的管道直接在调用方法中处理错误,但它收到与上面的错误相同的错误。
这是我的服务方法的代码
createPartner(partner: Partner) {
return this.http.post(this.publicUrl + "partner", partner).pipe(catchError(this.handleError));
}
handleError(error: HttpErrorResponse) {
console.log(error);
return throwError(error);
}
Run Code Online (Sandbox Code Playgroud) 我需要向包含帖子列表和帖子总数的密钥的端点发出获取请求。
{
posts: [{}, {}, {}, ...],
total: 1000
}
Run Code Online (Sandbox Code Playgroud)
请求的偏移键决定返回的帖子数量。
// request
https://postBalzer.com/posts?offset=0&limit=50
Run Code Online (Sandbox Code Playgroud)
此请求返回 0 - 50 之间的帖子 如何使调用递归,直到使用 Angular HttpClientModule 获取所有帖子。
在这种情况下如何使用 Expand rxjs 运算符?
我正在尝试在 Angular 7 中创建一个简单的 API 服务,我可以将它包含在任何需要它的组件中。但是,每当我从组件调用它时,都会出现错误。例如,如果从我的组件中调用ApiService.read('/public/flavorsofcandy/')我得到:
ERROR TypeError: Cannot read property 'get' of undefined
现在,我不确定为什么会这样,但我觉得这是一件简单而愚蠢的事情。但是,我无处可找到为什么会发生这种情况。我觉得这是因为我没有完全理解与类和诸如此类的相关概念,而不是 Angular 7 本身。
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ApiService {
private baseUrl = "http://localhost:11000/";
private http: HttpClient;
public create = (req:string, options?:any) => {
this.http.post(this.baseUrl+req, options)
.subscribe(response=> {return response})
}
public read = (req:string, options?:any) => {
this.http.get(this.baseUrl+req,options)
.subscribe(response=> {return response})
}
public update = (req:string, options?:any) => {
this.http.put(this.baseUrl+req, options)
.subscribe(response=> …Run Code Online (Sandbox Code Playgroud) Angular HttpHeaders responseType: 'text' 。给予Type 'string' is not assignable to type 'json'。错误。我知道响应不是 JSON。我不明白如何更改类型?我想获取该文本(HTML)并在之后用正则表达式解析它。
代码
const httpOptions = {
headers: new HttpHeaders({
accept: '*/*',
contentType: 'application/x-www-form-urlencoded',
}),
responseType: 'text',
};
post = this.httpClient.post(destinationUrl, httpBody, httpOptions);
post.subscribe(
(res) => {
console.log(res)
},
(error) => {
console.error('download error:', error)
},
() => {
console.log('Completed')
},
);
Run Code Online (Sandbox Code Playgroud)
如您所见,响应类型是文本。由于我不明白的事情,我无法让它接受文本,因为它正在等待 json ...
这里我有一个疑问,如何在订阅中调用间隔方法并在满足条件后停止它
下面是我的代码
主要订阅方式
this.authservice.getdata().subscribe(response => {
console.log(res)
// Polling method
SetInterval(()=>{
this.getInterval();
},5000)
})
Run Code Online (Sandbox Code Playgroud)
间隔法:
getInterval(){
this.authservice.getIntervalData().subscribe(resp => {
console.log(resp)
this.responseStatus = resp
})
}
Run Code Online (Sandbox Code Playgroud)
在响应中它给出了 3 种类型的响应
继续
停止
终止
因此,在这里我需要在 Main 订阅方法中调用 getInterval() ,直到 GetInterval 给我 Proceed 作为响应,或者直到轮询后 1 分钟,我已经设置了运行间隔,如果满足这两个条件之一,我必须停止轮询。
注意:如果主订阅在成功时给出响应,那么我不需要轮询主订阅方法,那么只有我开始此轮询
更新: 下面的方法有效,但这里我需要两件事
如何设置变量并将响应存储在其中
我如何根据res设置布尔变量,就像响应来了一样
this.content =true 同样明智
因为当我尝试在 switchMap 中设置变量时,它不接受
this.authservice.getdata().pipe( switchMap(resp => timer(0, 5000).pipe( // 需要将此响应存储在全局变量中,以便可以用于进一步 switchMap(t => this.authservice .getIntervalData( <第一个响应参数> ).pipe( map(data => [data, t]))) takeWhile(([data, t]) => data !== 'TERMINATE' && t < 12), …
大家好,我是 Angular 的新手,我遇到了这个错误:
\nERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiCallServiceService -> _ApiCallServiceService -> _HttpClient -> _HttpClient]: \n NullInjectorError: No provider for _HttpClient!\n at NullInjector.get (core.mjs:5605:27)\n at R3Injector.get (core.mjs:6048:33)\n at R3Injector.get (core.mjs:6048:33)\n at injectInjectorOnly (core.mjs:911:40)\n at Module.\xc9\xb5\xc9\xb5inject (core.mjs:917:42)\n at Object.ApiCallServiceService_Factory [as factory] (api-call-service.service.ts:8:35)\n at core.mjs:6168:43\n at runInInjectorProfilerContext (core.mjs:867:9)\n at R3Injector.hydrate (core.mjs:6167:17)\n at R3Injector.get (core.mjs:6037:33)\nRun Code Online (Sandbox Code Playgroud)\n应用程序组件.ts
\nimport { Component } from \'@angular/core\';\nimport { CommonModule } from \'@angular/common\';\nimport { RouterOutlet } from \'@angular/router\';\nimport {FormComponent} from "./component/form/form.component";\nimport {HttpClientModule} from "@angular/common/http";\n\n@Component({\n selector: \'app-root\',\n standalone: true,\n imports: …Run Code Online (Sandbox Code Playgroud) 我无法使用rxjs take()运算符限制模板中的显示结果,模板始终显示所有记录.
api http://jsonplaceholder.typicode.com/users返回10个元素,我只想拿四个元素.
[service]
public getData(): Observable<User[]> {
return this.http.get<User[]>(`http://jsonplaceholder.typicode.com/users`).pipe(
take(4)
);
}
[component]
export class GridComponent implements OnInit {
_data : Observable<User[]>;
constructor(public _ds : DataService) {
}
ngOnInit() {
this._data = this._ds.getData();
}
}
[template]
<tr *ngFor="let d of _data | async">
<td>{{d.id}}</td>
<td>{{d.name}}</td>
<td>{{d.email}}</td>
<td>{{d.phone}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud) angular ×10
rxjs ×3
typescript ×3
angular6 ×1
class ×1
ecmascript-6 ×1
http-headers ×1
javascript ×1
recursion ×1
rxjs6 ×1