【问题标题】:Trouble with Angular 2 http.get methodAngular 2 http.get 方法的问题
【发布时间】:2018-05-25 04:39:35
【问题描述】:

问候。我正在尝试通过重建我之前使用相同后端代码所做的项目的前端来学习 Angular 2。最初的项目在前端使用 jQuery,在后端使用 PHP。我正处于想开始将前端连接到后端的地步,但我似乎无法让它工作。

目前我的原始后端代码在本地主机上的 apache2 上运行,并且测试 Angular 应用程序在本地主机上运行:4200。我试图访问的后端文件位于 ajax.php(路径是 'localhost/pokemon/ajax.php'),并且我在该文件中有一行用于在引用该文件时记录错误。

当我从我的 Angular 2 服务执行 http.get 并将结果记录在我的组件上时,我得到 [object Object] 并且 ajax.php 没有记录消息,所以它似乎没有被调用。

这是我的代码。 I 有问题的函数在每个文件的底部附近。

hero.service.ts

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';

  constructor(
    private messageService: MessageService,
    private http: HttpClient
  ) { }


  getHeroes (): Observable<Hero[]> {
    //return this.http.get<Hero[]>(this.heroesUrl)
    return null;
  }

  getHero(id: number): Observable<Hero> {
    // TODO: send the message _after_ fetching the hero
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    return of(HEROES.find(hero => hero.id === id));
  }

  //calls http.get
  testFunc() {
    console.log("Test func is being called in the service");
    return of(this.http.get('localhost/pokemon/ajax.php?method=getTypes'));
  }
}

还有我要测试的组件

heroes.component.ts

import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    console.log("Init is being called");
    //this.getHeroes();
    this.testFunc();
  }

  //calls the test function
  testFunc(): void {
    console.log("Test function is being called");
    this.heroService.testFunc()
      .subscribe(
        data => console.log("Got this: " + data),
        err => console.log("Error " + err),
        () => console.log("Done!")
      );
  }
}

我也尝试从具有相同应用的实时服务器获取数据,但结果相同。

谢谢!

【问题讨论】:

  • 我不确定url 的正确性,但您在控制台中获得[object] 的原因是因为日志记录语法。使用此语法代替console.log("Got this", data);,对错误回调日志执行相同操作。
  • 返回不是错误的吗?如果我是正确的,http.get 已经返回了一个 observable。现在你返回一个 Observable>。而且由于 http.get 的 observable 没有被订阅,它永远不会调用。
  • 使用console.log(JSON.parse(data));
  • 你不需要of(this.http.get()),因为this.http.get() 已经返回了一个observable。您正在将一个可观察对象包装在另一个对象中!你可以return this.http.get('...')
  • 感谢 cmets。我改变了记录错误的方式并停止返回一个可观察的可观察的,它似乎已经清除了事情。现在我遇到了另一个(神秘的)错误,但我想我会为此提出一个新问题。干杯。

标签: angular apache http


【解决方案1】:

此代码可能对您有所帮助

this.heroService.testFunc().subscribe(
            (data => {
                if (data["_body"] && data["_body"] != "") {
                     console.log(JSON.stringify(data["_body"]));

                };
            }),
            error => this.toastr.error('Something went wrong !!', 'Oops!', {showCloseButton: true})
        );

为您服务

 testFunc() {
        return this._http.post('http://localhost:4200(the port on which your php code running)/pokemon/ajax.php', user).map(() => "your method or "" ");
    }

如果您需要任何帮助评论

【讨论】:

    【解决方案2】:

    试试这样。它会工作

    getusers() {
        const headers = new Headers(
                 {
                     accept: 'application/json/'
                 });
             const options = new RequestOptions({ headers: headers });
         return this.http.get(this.url, options).map((response: Response) => response.json());
      } 
    

    在你的调用函数中 获取() {

      this.service.getusers().subscribe(a => {
        this.a = a;
        // console.log(a.length);
      });
      }
    

    【讨论】:

      【解决方案3】:

      所以我得到了一些非常有用的 cmets——我返回的 (http.get(..)) 把事情搞砸了,我没有正确地将收到的错误记录到控制台。

      它仍然没有像我预期的那样工作,但它足以继续前进,所以我将提出一个新问题,因为当前问题已基本解决。 谢谢大家!

      【讨论】:

        猜你喜欢
        • 2015-04-09
        • 2017-03-15
        • 2016-11-23
        • 2018-11-20
        • 2016-06-29
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多