Angular 2 http.get方法问题

时间:2018-05-25 04:39:35

标签: angular apache http

拜。我正在尝试通过重建我之前使用相同后端代码执行的项目的前端来学习Angular 2。原始项目在前端使用jQuery,在后端使用PHP。我想要开始将前端挂到后面,但我似乎无法让它工作。

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

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

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

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!")
      );
  }
}

我还试图从具有相同应用程序的实时服务器获取数据,但结果是相同的。

谢谢!

3 个答案:

答案 0 :(得分:0)

此代码可能会对您有所帮助

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 "" ");
    }

如果您需要任何帮助评论

答案 1 :(得分:0)

试试这样。它会起作用

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());
  } 

并在您的通话功能中  get(){

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

答案 2 :(得分:0)

所以我得到了一些非常有帮助的评论 - 我正在返回(http.get(..)),它搞砸了事情并且我没有正确记录我收到的错误。< / p>

它仍然没有像我预期的那样工作,但它足以继续前进,因此我将开启一个新问题,因为目前的问题基本上已经解决了。 谢谢大家!

相关问题