我在从ActivatedRoute获取参数以用于Http Get请求时遇到问题。基本上,我正在尝试获取this.link并在我的DataService上使用它来发出Http Get请求。当用户访问DetailsComponent时,我不想使用该route参数来形成Http get请求。例如,用户导航到example.com/animal/cat,我想在我的Get请求中使用cat。但是,每次我尝试时,都会收到回复,告诉我this.link未定义。
GET http://123.123.123.123/api/v2/_table/animal/undefined?related=move_by…k&api_key=7201dd61c71 404 (Not Found)
的DataService:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subscription, Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map'
@Injectable()
export class DataService {
constructor(private dataService: Http) {
}
urlprefix = 'http://123.123.123.123/api/v2/_table/animal/';
api = '&api_key=7201dd61c71';
getData(url): Observable<any> {
return this.dataService.get(this.urlprefix + url + this.api);
}
}
DetailComponent
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ROUTER_DIRECTIVES, ActivatedRoute, Router } from '@angular/router';
import { Response } from '@angular/http';
import { Subscription } from 'rxjs/Rx';
import { DataService } from '../../data.service';
@Component({
moduleId: module.id,
selector: 'animal-details',
templateUrl: 'animal-details.component.html',
styleUrls: ['animal-details.component.css'],
directives:[ROUTER_DIRECTIVES],
providers:[DataService]
})
export class AnimalDetailsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
animal = {};
link: string;
table = 'animal/'
private url = this.table + this.link + '?related=family';
constructor(private activatedRoute: ActivatedRoute, private dataService: DataService, private router: Router) {
this.subscription = activatedRoute.params.subscribe(
(param: any) => this.link = param['link']
);
}
ngOnInit() {
this.dataService.getData(this.url)
.map((response: Response) => response.json())
.subscribe(
(data: any) => {this.animal = data},
err => { this.router.navigate(['error404']) }
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
我可以通过字符串插值在{Details}中清楚地看到params正确输出:{{link}}。无论我尝试什么,它仍然在Get请求中显示为未定义,并且我总是被给出错误。我很感激任何帮助。
编辑:下面的新工作代码 DataService的:
export class DataService {
constructor(private dataService: Http) {
}
urlprefix = 'http://123.123.123.123/api/v2/_table/';
api = '&api_key=7201dd61c71';
getData(table, link, url): Observable<any> {
return this.dataService.get(this.urlprefix + table + link + url +this.api);
}
}
AnimalDetailsComponent:
link: string;
table = 'animal/';
private url = '?related=family';
ngOnInit() {
this.dataService.getData(this.table, this.link, this.url)
.map((response: Response) => response.json())
.subscribe(
(data: any) => {this.animal = data},
err => { this.router.navigate(['error404']) }
);
}
答案 0 :(得分:0)
您的详细信息组件的路径网址是什么?如果您使用查询参数调用详细信息,例如 http://localhost/details?id=123 ,请替换?用;,新的路由器使用;在网址( http://localhost/details;id=123 )。
然后在 AnimalDetailsComponent 中将this.subscription...
移至 ngInit()的开头。路由在Angular生命周期中初始化,而不是在构造函数期间。