我正在向具有以下路由的服务器发出请求:
app.use('/401', (req, res) => res.status(401).end());
app.use('/403', (req, res) => res.status(403).end());
app.use('/404', (req, res) => res.status(404).end());
app.use('/500', (req, res) => res.status(500).end());
app.use('/502', (req, res) => res.status(502).end());
app.use('/503', (req, res) => res.status(503).end());
app.use('/504', (req, res) => res.status(504).end());
Run Code Online (Sandbox Code Playgroud)
当我用Angular(/404,{})发出请求时:
public async post(path: string, data: object): Promise<Response> {
try {
return await this.http.post(path, data).toPromise();
} catch (err) {
console.log('err', err);
throw err;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到:
ok: false
status: 0
statusText: ""
type: 3
Run Code Online (Sandbox Code Playgroud)
在Chrome控制台中,我看到发出了请求,OPTIONS并且确实返回了404:
Request URL: http://localhost:3000/404/ …Run Code Online (Sandbox Code Playgroud) 我正在切换以使用新的 HttpClient 角度。
正在调用的 API 以一种格式返回 json 数据。我想获取这些数据并将其转换为适合 UI 使用的打字稿模型类。
我之前这样做的方法是使用 map 函数,例如
return this.httpClient.get(url, { headers: headers })
.map(mapFunction)
.catch(errorFunction);
Run Code Online (Sandbox Code Playgroud)
map 函数在模型对象中执行转换 api 响应的繁重工作,例如
const mapFunction =
(response: Response) => {
const data = response.json();
const contacts: Contact[] = [];
let i = 0;
for (const result of data.resourceResults) {
i = i + 1;
const contact: Contact = new Contact();
contact.role = result.r
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎很麻烦,我基本上是在寻找一种方法来将对象从 api 响应类型映射到 ui 模型类型,而不必为每个请求使用自定义映射函数。
我只是尝试使用 Angular Universal 预渲染一个组件,该组件使用 httpClient 从/static应用程序本身的文件夹中获取数据。
我猜该文件不可访问,因为应用程序在预渲染时没有在任何服务器上运行。获取路径是相对的。稍后在远程服务器上获取文件有效,但是在预渲染期间“远程服务器”不可用还是?如何使这工作?
我确实收到了一个错误 [ERROR],这是由httpClient.get(). 捕获错误错误消息为空。
基本上我有服务
doReqeust() = {
return this.httpClient.get("./static/get.json")
}
Run Code Online (Sandbox Code Playgroud)
并在组件中
onInit() {
this.data = this.myService.doRequest();
}
Run Code Online (Sandbox Code Playgroud)
并且视图比它通过异步管道绑定
{{ data.response.title | async }}
Run Code Online (Sandbox Code Playgroud)
静态是项目中的静态文件夹。
angular-http angular-http-interceptors angular-universal angular angular-httpclient
我试图发布一组未发送到服务器的数据:
网络服务:
deleteCategory() {
return this.http.post('http://www.demo/webapi/deletecategory', {
headers: {
"Authorization": "Token " + this.token,
"Content-Type": "application/x-www-form-urlencoded"
},
withCredentials: true
}
)
}
Run Code Online (Sandbox Code Playgroud)
在 ts 文件中
onDelete() {
this.userService.deleteCategory().subscribe(response => {
this.selectedArray = [];
for (var i = 0; i< this.selection._selected.length; i++){
this.selectedArray.push(this.selection._selected[i].category_id) ;
console.log(' selected value:', this.selectedArray);
}
})
}
Run Code Online (Sandbox Code Playgroud)
在 html 中
<button class="btn-danger pull-right" (click)="onDelete()" type="button" >Delete</button>
Run Code Online (Sandbox Code Playgroud) MySharedService我有一个多个组件使用的服务(我们称之为)。在内部MySharedService,我调用了另一个进行 API 调用的服务。MySharedService保存一个在我调用后分配的 JavaScript 对象GET。
我的问题是我的组件依赖该 JavaScript 对象在其构造函数中设置它们的值。当由于 API 调用尚未完成而导致 JavaScript 未定义时,我该如何设置它们的值?这是一个示例:
API服务
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
/* Other imports */
@Injectable()
export class ApiService {
constructor(private http: HttpClient) { }
getTestData(): Observable<MyDataInterface> {
const API_URL = 'some_url_here';
return this.http.get<MyDataInterface>(API_URL, { observe: 'response' });
}
}
Run Code Online (Sandbox Code Playgroud)
我的共享服务
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable'; …Run Code Online (Sandbox Code Playgroud) 在以前的 Angular 版本中,我使用的finally()就像下面的代码一样
constructor(
private http: Http
) { }
const headers = new Headers({ 'Authorization': this.authenticate.getToken(), 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
return this.http.put(Globals.SERVER_URL + '/alert/exempted?_id=' + alertId + '&isExempted=' + status + '&app_id=' + app_id, options )
.map(this.extractData)
.catch(this.handleError)
.finally(() => {
this.exceptionSubject.next();
});
Run Code Online (Sandbox Code Playgroud)
但是现在使用 Angular 7 时,我不能再使用它了。如何在代码中插入finally(HttpClient)?这是我现有的代码:
constructor(
private http: HttpClient
) { }
const header = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.get(Globals.ATTENDANCE_URL + '/individual_employment_setting/detail/' + id, { headers: header }) …Run Code Online (Sandbox Code Playgroud) 我正在通过课程学习角度,目前我正在学习拦截器。课程中的角度版本不是 17,但我在本地使用的版本是。因此,在第一次尝试通过类实现拦截器之后,由于拦截没有发生,因此无法正常工作。
当我查看 net 并发现我们可以设置一个拦截常量并且我们可以在 app.config.ts 中提供它时,即使这样做之后它也不起作用。所以我真的被困住了。任何帮助,将不胜感激。这是我的文件:
应用程序组件.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { Post } from './Post';
import { PostService } from './post-service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, HttpClientModule, FormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit, OnDestroy …Run Code Online (Sandbox Code Playgroud) 我正试图从这个api获取json数据:http://chartapi.finance.yahoo.com/instrument/1.0/NFLX/chartdata;type=quote;range=1d/json 我不知道怎么弄进入返回的finance_charts_json_callback().
我正在使用Angular 2的http.get():
loadData() {
return this.http
.get(this.url)
.map((res) => res.json())
.subscribe((data) => console.log(data));
}
Run Code Online (Sandbox Code Playgroud)
当它到达时=> res.json(),它会抛出此错误:
EXCEPTION:SyntaxError:意外的令牌i
我正在尝试将Http请求迁移到HttpClient请求.我能够迁移我的post查询但我在迁移get查询时遇到问题.当我这样做时,我的后端没有分别收到任何参数,它告诉我没有提供参数并且为空.
我做错什么了吗?
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
constructor(private httpClient: HttpClient) {}
findItems() {
let params: HttpParams = new HttpParams();
params.set('something', 'hello');
this.httpClient.get<any[]>('http://localhost:3000/apath/', {params})
.subscribe((results: any[]) => {
console.log(results);
}, (errorResponse: any) => {
console.error(errorResponse);
});
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
我正在做一个angular2项目,在assets文件夹中有一个文件,并且创建了一个在运行应用程序时下载文件的按钮。
我看到上述问题有很多解决方案,所以我很困惑。你能帮忙吗?
<button pButton type="button" (click)="f1()" label="Download Sample Defaults
XML File"></button>
Run Code Online (Sandbox Code Playgroud)
我需要f1()的代码,当单击上面的按钮时,该代码可以帮助我将文件下载到我的“下载”文件夹中。帮助表示赞赏。谢谢
angular ×10
angular-http ×10
typescript ×3
angular-httpclient-interceptors ×1
finally ×1
http ×1
http-post ×1
httpclient ×1
rxjs ×1