我无法理解范围在Angular中的工作原理。
我使用各种关键字进行了大量的Google搜索,并创建了一些本地实验。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PeopleService {
givenProperty: string = "GivenString";
givenFunction() {
this.givenProperty = "NewGivenString";
var one = 1;
if (one == 1) {
return this.givenProperty;
}
}
}
为什么givenProperty
中的givenFunction
不在范围内?我怎样才能在范围内制作它以便我可以更改它并在功能之外再次使用它?
Angular 2.0使用的是新概念而不是$ scope。 HTML元素在事件,属性和属性中已经具有易于绑定的接口。对于您的属性GivenProperty
,您需要在HTML模板中使用它来查看结果。
此外,Angular 2不会像AngularJS一样在组件之间共享数据。它通过在模板中使用数据并将事件传递给其他组件来绑定数据。
查看以下链接:https://angular.io/guide/component-interaction https://angular.io/guide/template-syntax
问题是一个角色初学者的错误。从未调用上述问题中的函数。要调用它需要在构造函数中的函数。一旦我将它添加到构造函数中,它就像我预期的那样工作。我会删除StackOverflow不会让我的问题。
export class AppComponent {
givenProperty: string = "GivenString";
constructor() {
this.givenProperty = this.givenFunction();
}
givenFunction() {
this.givenProperty = "NewGivenString";
var one = 1;
if (one == 1) {
return this.givenProperty;
}
}
}