0

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 ?

2
  • Could you add more information on the context ? Are you trying to add a variable in a function or in a class ? Commented May 21, 2020 at 12:07
  • What is the error you are getting? Commented May 21, 2020 at 12:07

1 Answer 1

3

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;
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks now i get it, could you please tell when to use ":" or "=" and " " " or " ' "
@user1187282 You use : to define the type of the variable. In our case we don't need it because we initialized it to a static value, which is a string. If we didn't we would want to define it as string ( baseUrl: string; ) and the assign it else where in the code ( this.baseUrl = '...'; ) . As for the quote it does not really matther.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.