【发布时间】: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。我改变了记录错误的方式并停止返回一个可观察的可观察的,它似乎已经清除了事情。现在我遇到了另一个(神秘的)错误,但我想我会为此提出一个新问题。干杯。