如何在服务 class 和控制器 class (typescript/angular) 中共享模型变量
How can model variables can be shared in both Service class and controller class (typescript/angular)
我有控制器 class、服务 class 和模型 class。我想知道如何在 Controller 和 Service 中访问相同的模型 classes.
例如:
控制器 Class :
import { SearchModel } from "../../models/SearchModel";
import { SearchService } from "../../components/SearchService";
export class SearchController {
public searchModel: SearchModel;
static $inject = ['searchService'];
constructor(private searchService:SearchService) {
this.searchService = searchService;
}
public controllerMethod() {
console.log(this.searchModel.searchKeyword); //This works.
this.searchModel.searchKeyword = "CheckIfSharedObject";
this.searchService.serviceMethod();
}
}
服务Class:
import { SearchModel } from "../../models/SearchModel";
export class SearchService {
public searchModel: SearchModel;
constructor() { }
public serviceMethod() {
// This will not work. i.e this wont print 'CheckIfSharedObject'
console.log(this.searchModel.searchKeyword);
}
}
型号Class:
export class SearchModel {
constructor (
public searchKeyword: string
)
}
从上面的示例中,我希望控制器和服务在 classes 中共享模型变量 searchKeyword。
当我们将模型 class 对象传递给 serviceMethod 时它起作用,但我不想那样做。有没有一种方法可以在不显式地将模型 Class 对象传递给服务 class.
的情况下使其工作
I want controller and service to share the model variable searchKeyword in both the classes
可以使用 angularjs 服务 对 model
进行建模。这将使模型成为可以在控制器和服务之间共享的单例。
事实上,我什至会说您的服务确实应该成为典范。这样一来,您将只有 "controller" + "service",但如果您愿意,可以随意拥有三样东西。
我有控制器 class、服务 class 和模型 class。我想知道如何在 Controller 和 Service 中访问相同的模型 classes.
例如:
控制器 Class :
import { SearchModel } from "../../models/SearchModel";
import { SearchService } from "../../components/SearchService";
export class SearchController {
public searchModel: SearchModel;
static $inject = ['searchService'];
constructor(private searchService:SearchService) {
this.searchService = searchService;
}
public controllerMethod() {
console.log(this.searchModel.searchKeyword); //This works.
this.searchModel.searchKeyword = "CheckIfSharedObject";
this.searchService.serviceMethod();
}
}
服务Class:
import { SearchModel } from "../../models/SearchModel";
export class SearchService {
public searchModel: SearchModel;
constructor() { }
public serviceMethod() {
// This will not work. i.e this wont print 'CheckIfSharedObject'
console.log(this.searchModel.searchKeyword);
}
}
型号Class:
export class SearchModel {
constructor (
public searchKeyword: string
)
}
从上面的示例中,我希望控制器和服务在 classes 中共享模型变量 searchKeyword。
当我们将模型 class 对象传递给 serviceMethod 时它起作用,但我不想那样做。有没有一种方法可以在不显式地将模型 Class 对象传递给服务 class.
的情况下使其工作I want controller and service to share the model variable searchKeyword in both the classes
可以使用 angularjs 服务 对 model
进行建模。这将使模型成为可以在控制器和服务之间共享的单例。
事实上,我什至会说您的服务确实应该成为典范。这样一来,您将只有 "controller" + "service",但如果您愿意,可以随意拥有三样东西。