为什么要自动调用http服务

时间:2017-11-02 12:36:00

标签: angular angular-routing angular-services angular-http

Http service获取数据,然后传递到cached service compoenent订阅cached service并在启动时发出http请求。

当用户点击锚标记时,应该调用http get服务。单击锚标签导航到传递id的路由,然后根据获取数据的ID并显示视图。

但是,当我加载应用时,它突然发出以下错误id = undefined 我刚启动应用程序没有或点击发出这些请求

GET https://gateway.marvel.com/v1/public/characters/undefined?apikey 404 (Not Found)
GET https://gateway.marvel.com/v1/public/characters/undefined?apikey 404 (Not Found)

//从服务器

获取数据的HTTP数据服务
getChar(): Observable<any> {
    const characters = this.http.get('https://gateway.marvel.com:443/v1/public/characters?apikey');
    const comics = this.http.get('https://gateway.marvel.com:443/v1/public/comics?apikey');
    const characterDetail = this.http.get(`${this.urlChar}${this.charId}${this.apiKey}`);
    const comicsDetail = this.http.get(`${this.urlCom}${this.comicsId}${this.apiKey}`);
    return Observable.forkJoin([characters, comics, characterDetail, comicsDetail]);
    // .map(responses => {
    //    // responses[0] => cars
    //    // responses[1] => bikes
    // });

//将服务器中的数据存储到本地变量的服务

getComDe(id: string): any {
    this.dt.comicsId = id;
    this.dt.getChar().subscribe((responses: Response) => {
      this.comDd = responses[3].json().data.results;
      this.comDtls = this.chDd;
      console.log(this.comDtls);
    });

//组件订阅并传递id

ngOnInit() {
    this.comDl.getComDe(this.route.snapshot.params['id']);
  }

1 个答案:

答案 0 :(得分:0)

是的,这就是你的代码编写方式:

// template side
<li class="col-md-4" *ngFor="let comics of comicsList"> <a [routerLink]="['comics/', comics.id]">
// component side
this.comDl.getComDe(this.route.snapshot.params['id']);

这样你就可以获得comic_id或character_id 但是你有两个写代码

const characterDetail = this.http.get(`${this.urlChar}${this.charId}${this.apiKey}`);
const comicsDetail = this.http.get(`${this.urlCom}${this.comicsId}${this.apiKey}`);

这就是原因,

GET https://gateway.marvel.com/v1/public/characters/undefined?apikey 404 (Not Found)
GET https://gateway.marvel.com/v1/public/characters/undefined?apikey 404 (Not Found)

getChar()功能替换为:

getChar(): Observable<any> {

    var Observables = [];
    Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/characters?apikey'));
    Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/comics?apikey'));

    if(this.charId)
        Observables.push(this.http.get(`${this.urlChar}${this.charId}${this.apiKey}`));
    if(this.comicsId)
        Observables.push(this.http.get(`${this.urlCom}${this.comicsId}${this.apiKey}`));

    return Observable.forkJoin(Observables);
    // .map(responses => {
    //    // responses[0] => cars
    //    // responses[1] => bikes
    // });
}