Tuesday, 12 July 2016

Angular - what variables need to be defined inside/outside of the exported class?



In the Angular tutorial here: https://stackblitz.com/angular/qmgqmlrqmye?file=src%2Fapp%2Fhero.service.ts



We have to define httpOptions outside of the exported HeroService class and heroesUrl inside of the class. Moving either one to inside or outside of the class breaks the application. What is the reason for this? How do I know which variables have to be defined inside or outside?




Code sample:



import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({ providedIn: 'root' })
export class HeroService {


private heroesUrl = 'api/heroes'; // URL to web api

constructor(
private http: HttpClient,
private messageService: MessageService) { }

/** GET heroes from the server */
getHeroes (): Observable {
return this.http.get(this.heroesUrl)

.pipe(
tap(heroes => this.log(`fetched heroes`)),
catchError(this.handleError('getHeroes', []))
);
}
...

Answer



You can put either of those things inside or outside the class. I'd personally put all of those things inside of the class though since they are obviously a part of it.




Members defined inside of a class are either prefaced with private meaning they can only be referenced from within the class, public meaning you can reference them from outside of the class or without either which just means its implicitly public.



Let's take a look at how we'd move httpOptions inside the class. Since its an implementation detail that only the class needs to know about, it makes sense to define it as a private member:
private httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
}



Now, since it is a class member, in order to access it we must use this. this is just a reference to the class's context so we're saying give me the member in this class.



Anywhere you see httpOptions being referenced change it to this.httpOptions




Hope you can see how you would do it the other way around and have them defined as consts outside of the class.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...