无法访问组件中的服务变量 - Angular2
Can't access the service variable in component - Angular2
我正在服务中进行 HTTP 调用并将 return 数据分配给服务变量。现在,当我尝试访问组件中的该服务变量时,它在控制台中记录为未定义。但是,当我将日志代码放入服务本身时它会被记录下来,但在组件中时它不起作用。
下面是我的代码供参考:
hero.service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './hero';
@Injectable()
export class HeroService {
heroes: Hero[];
hero: Hero;
gbl: Hero[];
private heroesUrl = 'SERVICE URL';
constructor (private http: Http) {}
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json()['data'];
this.gbl = body;
return body || { };
}
private handleError (error: Response | any) {
Handles Error
}
getHero(id: number): Observable<Hero> {
return this.getHeroes()
.map(heroes => heroes.find(hero => hero.id == +id));
}
}
英雄-list.component
import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { HeroService } from './hero.service';
import { Hero } from './hero';
@Component({
template: `Template`
})
export class HeroListComponent {
errorMessage: string;
heroes: Hero[];
listlcl: Hero[];
id: number;
public listheroes: Hero[];
mode = 'Observable';
private selectedId: number;
constructor (
private heroService: HeroService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() { this.getHeroes() }
getHeroes() {
this.id = this.route.snapshot.params['id'];
console.log(this.id);
this.heroService.getHeroes()
.subscribe(
heroes => {
this.heroes = heroes;
this.listlcl = this.heroService.gbl;
console.log(this.listlcl);
},
error => this.errorMessage = <any>error);
}
isSelected(hero: Hero) { return hero.id === this.id; }
onSelect(hero: Hero) {
this.router.navigate(['/hero', hero.id]);
}
}
您的代码的问题是当您在地图中使用 extractData
时 this
变量不是您的服务实例,它被分配给 http 请求的映射器。
您可以简单地将您的函数转换为箭头函数,以便将范围设置为服务实例,如下所示,您将能够在组件中看到现在已正确分配给服务实例的变量值。
private extractData = (res: Response) => {
let body = res.json()['data'];
this.gbl = body;
return body || { };
}
检查这个 Plunker!!
希望对您有所帮助!!
一些参考,取自typescript documentation、
this 和箭头函数
In JavaScript, this is a variable that’s set when a function is
called. This makes it a very powerful and flexible feature, but it
comes at the cost of always having to know about the context that a
function is executing in. This is notoriously confusing, especially
when returning a function or passing a function as an argument.
We can fix this by making sure the function is bound to the correct
this before we return the function to be used later. This way,
regardless of how it’s later used, it will still be able to see the
original deck object. To do this, we change the function expression to
use the ECMAScript 6 arrow syntax. Arrow functions capture the this
where the function is created rather than where it is invoked
我正在服务中进行 HTTP 调用并将 return 数据分配给服务变量。现在,当我尝试访问组件中的该服务变量时,它在控制台中记录为未定义。但是,当我将日志代码放入服务本身时它会被记录下来,但在组件中时它不起作用。
下面是我的代码供参考:
hero.service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './hero';
@Injectable()
export class HeroService {
heroes: Hero[];
hero: Hero;
gbl: Hero[];
private heroesUrl = 'SERVICE URL';
constructor (private http: Http) {}
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json()['data'];
this.gbl = body;
return body || { };
}
private handleError (error: Response | any) {
Handles Error
}
getHero(id: number): Observable<Hero> {
return this.getHeroes()
.map(heroes => heroes.find(hero => hero.id == +id));
}
}
英雄-list.component
import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { HeroService } from './hero.service';
import { Hero } from './hero';
@Component({
template: `Template`
})
export class HeroListComponent {
errorMessage: string;
heroes: Hero[];
listlcl: Hero[];
id: number;
public listheroes: Hero[];
mode = 'Observable';
private selectedId: number;
constructor (
private heroService: HeroService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() { this.getHeroes() }
getHeroes() {
this.id = this.route.snapshot.params['id'];
console.log(this.id);
this.heroService.getHeroes()
.subscribe(
heroes => {
this.heroes = heroes;
this.listlcl = this.heroService.gbl;
console.log(this.listlcl);
},
error => this.errorMessage = <any>error);
}
isSelected(hero: Hero) { return hero.id === this.id; }
onSelect(hero: Hero) {
this.router.navigate(['/hero', hero.id]);
}
}
您的代码的问题是当您在地图中使用 extractData
时 this
变量不是您的服务实例,它被分配给 http 请求的映射器。
您可以简单地将您的函数转换为箭头函数,以便将范围设置为服务实例,如下所示,您将能够在组件中看到现在已正确分配给服务实例的变量值。
private extractData = (res: Response) => {
let body = res.json()['data'];
this.gbl = body;
return body || { };
}
检查这个 Plunker!!
希望对您有所帮助!!
一些参考,取自typescript documentation、
this 和箭头函数
In JavaScript, this is a variable that’s set when a function is called. This makes it a very powerful and flexible feature, but it comes at the cost of always having to know about the context that a function is executing in. This is notoriously confusing, especially when returning a function or passing a function as an argument.
We can fix this by making sure the function is bound to the correct this before we return the function to be used later. This way, regardless of how it’s later used, it will still be able to see the original deck object. To do this, we change the function expression to use the ECMAScript 6 arrow syntax. Arrow functions capture the this where the function is created rather than where it is invoked