<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
</script>
</body>
</html>
在用角度代码编写代码时,iam有点困惑如何将html文件的数据绑定到变量...您可以通过给出and并做一点解释来取悦我。
答案 0 :(得分:1)
使用Angular,您需要拥有*.component.html
,*.component.ts
和*.module.ts
。
在您的*.component.ts
中,您将拥有以下内容:
import {...} from '...';
import { HttpClient } from '@angular/common/http';
@Component({...})
export class MyComponent implements OnInit {
public myWelcome: any;
constructor(private http: HttpClient){}
ngOnInit() {
let url = 'whatever url you need';
this.http.get<any>(url)
.subscribe(response => {
this.myWelcome = response.data;
//Handle success
}, error => {
//Handle error
});
}
}
HttpClient
将执行HTTP GET来获取数据。然后,响应值将存储在myWelcome
变量中,并可以在HTML内部使用。
在您的*.component.html
<h1>{{myWelcome?}}</h1>
如果值为空,?
就在那里,它不会破坏您的页面。
这是在Angular中执行此操作的基础