简体   繁体   English

如何在角度/打字稿中声明变量

[英]How to declare variable in angular/typescript

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我是 Angular/Typescript 的新手,所以我尝试了一个教程,当他创建服务时,他将 url 设置如下

 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:我之前读过 Typescritpt 中的变量是用 var 和 let 声明的,所以当我厌倦了将代码更新为:

  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.既然您说您正在尝试创建服务,我假设您正在 class 中定义此变量。

When declaring class-wide variable, ( called properties ) you don't need the let keyword.声明类范围的变量(称为属性)时,您不需要let关键字。 Instead, you want to define it as private , public or protected .相反,您想将其定义为privatepublicprotected

In you case, I feel like a private variable would be more suitable.在你的情况下,我觉得private变量会更合适。 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.然后,您可以在服务函数中使用this关键字访问此变量。

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.在这里,我使用了一个 getter 来进行演示,但是您可以使用相同的语法来调用 XmlHTTPRequest 例如。

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.此外,由于这是一个 url 并且不太可能更改,因此您可以使用关键字readonly来防止它在代码的其他地方被更改。

export class MyService {
   private readonly baseUrl = 'https://localhost:44351/api/member/';
   /* ... */

   public getTheBaseUrl(): any {
     return this.baseUrl;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM