在TypeScript类中混合代码和属性

时间:2018-11-23 21:29:44

标签: angular typescript

我有一个简单的TypeScript类,定义如下:

export class Piece {
    Qty: number;
    Weight: number;
    Type: string;

    totalWeight() {
        return Qty * Weight;
    }
}

而且,我有一个Angular 5服务,该服务具有如下方法:

  get(id: number) {
      return this.http.get<Piece>(myAPIURL + id);
  }

我的Angular代码将其调用如下:

const myPiece: Piece;
this.myService.get(2).subscribe(data => myPiece = data);

说完一切后,变量“ myPiece”包含正确的数据;但是,没有附加totalWeight()方法。我想我理解为什么(因为服务器返回了数据/属性,但显然没有代码)。但是,有什么方法可以再次将数据与代码/方法结合起来吗?

我的背景是C#对象,但对Java / TypeScript还是很陌生。我猜想这可能与JavaScript中的原型继承有关?

有帮助吗?

1 个答案:

答案 0 :(得分:0)

您实际上需要从http调用实例化该类。 TypeScript只是具有类型提示的javascript,不能进行实际的转换,因为javascript没有此功能。因此,要使某类成为某个类,您确实必须使用 public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); // Add framework services. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Connection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider(); services.AddSession(); services.AddHttpContextAccessor(); services.AddSingleton(Configuration); services.AddScoped<IAppDbRepository, AppDbRepository>(); services.AddScoped<IActiveDirectoryUtility, ActiveDirectoryUtility>(); services.AddScoped<IActiveDirectoryManager, ActiveDirectoryManager>(); services.AddHostedService<LdapManager>(); services.AddScoped<ILdapManager, LdapManager>(); } In the LdapManager class I would like to call the UpdateUsers method every hour: public class LdapManager : ILdapManager, IHostedService { private IConfiguration _configuration = null; private Logging _logger; private List<string> ldapConnectorForDirectoryEntries = new List<string>(); public LdapManager(IConfiguration configuration) { _configuration = configuration; UpdateUsers(); SyncActiveDirectoryUsers(); } public void SyncActiveDirectoryUsers() { try { using (var waitHandle = new AutoResetEvent(false)) { ThreadPool.RegisterWaitForSingleObject(waitHandle, (state, timeout) => { UpdateUsers(); }, null, TimeSpan.FromHours(1), false); } } catch { throw; } } } 关键字

实例化它。
new

get(id: number) {
  return this.http.get<Piece>(myAPIURL + id).pipe(
    map((data) => ({ ...new Piece(), ...data}))
  )
}

无论您觉得更清晰