I'm new in Angular/Typescript, so i tried a folow a tutorial and when he created a service he set the url as below
baseUrl = 'https://localhost:44351/api/member/';
and i read before that variables in Typescritpt are declared with var and let, so when i tired to updated the code to:
var baseUrl = "https://localhost:44351/api/member/";
it gives me an error compilation, isn't that how we suppose to declare variable?
Since you said you are trying to create a service, i'm assuming your are defining this variable in a class.
When declaring class-wide variable, ( called properties ) you don't need the let
keyword. Instead, you want to define it as private
, public
or protected
.
In you case, I feel like a private
variable would be more suitable. In that case, you can do something lile this.
export class MyService {
private baseUrl = 'https://localhost:44351/api/member/';
/* ... */
}
You can then access this variable using the this
keyword, inside the service functions.
export class MyService {
private baseUrl = 'https://localhost:44351/api/member/';
/* ... */
public getTheBaseUrl(): any {
return this.baseUrl;
}
}
Here, I've used a getter to demonstrate, but you could use the same syntax to call an XmlHTTPRequest for example.
Also, since this is an url and very unlikely to change, you can use the keyword readonly
which prevent it from being alter elsewhere in the code.
export class MyService {
private readonly baseUrl = 'https://localhost:44351/api/member/';
/* ... */
public getTheBaseUrl(): any {
return this.baseUrl;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.