繁体   English   中英

Angular11前端与js和

[英]Angular11 FrontEnd with js and

我是初学者,需要 Angular 的帮助。 我已经寻找了许多 yt 指南和教程,但每个人都说不同的 hting。 我很想知道如何在 Angular11 中使用 API 和 HTTP 以及如何将 Js 字段连接到 html。(我是新手请帮忙)

欢迎来到 Angular!

使用 Angular 调用 REST API 的最佳方法是使用HttpClientModule

在您的 AppModule 中导入HttpClientModule

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [
  ...

  HttpClientModule,
  ...

],

所以,现在你可以使用 HttpClient 来调用 API

@Injectable({providedIn: "root"})
export class MyService {
  constructor(private httpClient: HttpClient) {}
  
  getSomething() {
   return this.httpClient.get<YourResponseType>(REST_API_URL).toPromise()
  }

  postSomething() {
   const body = {key: 'value'}
   return this.httpClient.post<YourResponseType>(REST_API_URL, body).toPromise()
  }

}

更多信息在这里: https://angular.io/api/common/http/HttpClientModule

关于“将 Js 字段连接到 html ”我认为您正在谈论与[(ngModel)]的双向数据绑定,并且您必须在使用它的每个模块中导入FormsModule

在 html 中:

<p>This is my name: {{name}}</p>
<input [(ngModel)]="name" ></input>

在您的 ts 组件中:

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss'],
})
export class MyComponent {

   public name: string;
} 

您可以在 p 上实时读取输入值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM