我在Angular2 Web应用程序上工作.我在typescript中创建了一个简单的类:
export class User {
firstName: string;
lastName: string;
nominative() : string {
return this.lastName + " " + this.firstName;
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用nominative类型UserI的对象时收到此错误:Error in :0:0 caused by: user.nominative is not a function.
我在AppComponent班上调用这个函数:
export class AppComponent implements OnInit {
name: string = "";
ngOnInit() : void {
let user = JSON.parse(sessionStorage.getItem("User")) as User;
if (user) {
this.name = user.nominative();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过以这种方式使用lambda表达式:
nominative = () : string => { ... …Run Code Online (Sandbox Code Playgroud) 我今天在这里,是因为我有一个问题,如标题所述,关于Angular中的类和接口。
从我的角度来看,我理解:
Typescript中使用了接口来进行类型检查,这些接口一直存在,直到进行编译并在生产中消失为止。接口也不能用于实例化。
来自ES6的类也用于类型检查,但它们会在编译后保留并在生产中生成代码。同样,它们用于实例化。
因此,基本上,如果我们在生产中不需要它们,而仅需要类型检查,则Interface是有用的。相反,如果我们在生产中需要它们(特别是用于实例化),则可以在这里使用Class。
我是正确的,还是我错过了有关类和接口的知识?
我正在尝试将响应对象从我的 angular 项目中的 HTTP Post 请求转换为Person我定义的类。我在 HTTP 服务中定义了一个通用的 post 方法,并在我的个人服务中调用它,将通用替换为Person. 所以,我想,既然我已经做了 HTTPresponse应该是一个Person,但它不是 - 它只是一个Object. 我需要它是 aPerson因为我的 Person 类上有一些我需要访问的自定义逻辑。我可以在我的个人服务中编写一个辅助方法,但我觉得这应该可行 - 特别是因为 VS Code 智能感知说response我的组件中的 是Person当我将鼠标悬停在它上面时。
这是我的代码:
http.service.ts
@Injectable()
export class HttpService {
baseUrl = 'https://baseurl.com';
constructor(private http: HttpClient) { }
post<T>(endpointUrl: string, body: any): Observable<T> {
const fullUrl = this.baseUrl + endpointUrl;
return this.http
.post<T>(fullUrl, body)
.pipe(
map(response => response as T)
);
}
} …Run Code Online (Sandbox Code Playgroud) 我制作了一个路由服务并想将它注入到我的导航组件中。但是当我调用它的方法时,它会抛出TypeError: routingService.getRequestedPage is not a function. 昨天我在另一个服务上遇到了一个非常相似的问题,不幸的是我忘记了我是如何解决这个问题的。我用终端生成了服务。
src/app/nav/nav.component.ts 构造函数:
constructor(private templateService: TemplateService, private routingService: RoutingService) {
this.getTemplates();
if (this.routingService.getRequestedPage() === 'home') {
this.showHome();
}
}
Run Code Online (Sandbox Code Playgroud)
src/app/nav/nav.component.ts 进口:
import {RoutingService} from '../shared/routing.service';
Run Code Online (Sandbox Code Playgroud)
src/app/shared/routing.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class RoutingService {
private requestedPage: string;
constructor() {
this.requestedPage = 'home';
}
requestPage(page: string) {
this.requestedPage = page;
}
getRequestedPage() {
return this.requestedPage;
}
}
Run Code Online (Sandbox Code Playgroud)