加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

api – angular2 http.get()不向服务器发送请求

发布时间:2020-12-17 10:24:10 所属栏目:安全 来源:网络整理
导读:我正试图从我的角度应用程序对localhost执行一个get请求到我的api.但由于某种原因,角度http客户端似乎不执行get请求. 我可以在我的api服务器上看到没有得到请求.这导致了错误. api工作正常我试着做一个卷曲,我得到了预期的结果. EXCEPTION: Uncaught (in pro
我正试图从我的角度应用程序对localhost执行一个get请求到我的api.但由于某种原因,角度http客户端似乎不执行get请求.

我可以在我的api服务器上看到没有得到请求.这导致了错误. api工作正常我试着做一个卷曲,我得到了预期的结果.

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property ‘subscribe’ of undefined

api.service

import { Injectable } from '@angular/core';
import { Headers,Http,Response,URLSearchParams,RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ApiService {
    headers: Headers = new Headers({
        'Accept': 'application/json','Content-Type': 'application/json'
    });

    api_url: string = 'http://localhost:5001';

    constructor(private http: Http) { }

    private getJson(response: Response) {
        return response.json().results;
    }

    checkForError(response: Response): Response {
        if (response.status >= 200 && response.status < 300) {
            return response;
        } else {
            var error = new Error(response.statusText);
            error['response'] = response;
            Observable.throw(error);
        }
    }

    get(path: string,params: URLSearchParams): Observable<any> {
        return this.http
            .get(`${this.api_url}${path}/`,{ headers: this.headers })
            .map(this.checkForError)
            .catch(err => Observable.throw(err))
            .map(this.getJson);
    }

api.component.ts

import { Component,OnInit } from "@angular/core";
import { ApiService } from './api.service';

@Component({
    selector: 'item',templateUrl: './item.component.html'
})
export class ItemComponent implements OnInit {
    private itemData;
    private errorAlert;

    constructor(private apiService: ApiService) {}

      ngOnInit() {
          this.apiService.get('/items').subscribe(
              result => this.itemData = result,error => this.errorAlert = {msg: error,type: 'danger',closable: true},);
      }
}

附加控制台

也许您应该尝试回溯(或转发)问题:

从…开始:

this.http.get('/my/hardcoded/url').subscribe();

问题可能出在标题或插入的URL或任何地方.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读