【发布时间】:2018-12-13 11:01:21
【问题描述】:
我正在学习 Angular,选择了一个视频课程和一本 pdf 书,现在我对“导出”关键字的使用感到困惑......
课程一 (pdf) 使用 Angular 5 和 Visual Studio 2017。
课程二(视频)使用 Angular 6 和 Visual Studio Code。
以下线程讨论了导出以及为什么我们需要它的定义非常好:
Why does Typescript use the keyword "export" to make classes and interfaces public?
两个课程中的一个例子表明我的困惑......我只需要在正确的方向上快速踢一下,以克服这个小障碍。
Visual Studio 2017
示例项目让我在 ClientApp/App 文件夹中创建了一个界面文件夹,并在其中放置了一个界面“answer.ts”。这没有关键字“export”。
interface IAnswer {
Id: number;
QuestionId: number;
Text: string;
Value: number;
}
然后在组件中,使用它而不导入它。看看 loadData 函数,this.http.get<IAnswer[]>(url).subscribe。正在使用 IAnswer,它没有 export 关键字,也没有在组件中导入。
import { Component, Inject, Input, OnChanges, SimpleChanges } from "@angular/core";
import { Router } from "@angular/router";
import { HttpClient } from "@angular/common/http";
@Component({
selector: "answer-list",
templateUrl: "./answer-list.component.html",
styleUrls: ["./answer-list.component.css"]
})
export class AnswerListComponent implements OnChanges {
@Input() question: IQuestion;
answers: IAnswer[];
title: string;
constructor(private http: HttpClient,
@Inject("BASE_URL") private baseUrl: string,
private router: Router) {
this.answers = [];
}
ngOnChanges(changes: SimpleChanges) {
if (typeof changes['question'] !== "undefined") {
//alert(1);
// retrieve the question variable change info
var change = changes['question'];
// only perform the task if the value has been changed
if (!change.isFirstChange()) {
// execute the Http request and retrieve the result
this.loadData();
}
}
}
loadData() {
var url = this.baseUrl + "api/answer/All/" + this.question.Id;
this.http.get<IAnswer[]>(url).subscribe(res => {
this.answers = res;
}, error => console.error(error));
}
}
Visual Studio 代码
如果我不使用 export 关键字创建一个类,那么我不能在任何组件或服务中使用它,也需要导入。在 src/app/recipes 文件夹中放置了一个 recipe.model.ts。
export class Recipe {
constructor(public name: string, public description: string, public imagePath: string){
}
}
然后我有一个服务在这个例子中从/向 Firebase 获取/发布/推送数据,所以省略了与这个问题无关的代码。
import { Recipe } from "../../recipes/recipe.model";
@Injectable()
export class DataStorageService {
getRecipes(){
//get a authentication token
const token = this.authService.getToken();
const tokenQuery = '?auth=' + token
this.http.get(this.recipesNode + tokenQuery)
.pipe(
map(
(response: Response) => {
//we saved array of recipes
const recipes: Recipe[] = response.json();
return recipes;
}
)
)
.subscribe(
(recipes: Recipe[]) => {
this.recipeService.setRecipes(recipes);
}
);
}
}
【问题讨论】:
标签: angular typescript