Angular 的HttpClient应用

HttpClientModule, Observable

2025-05-29

Written by: tdtc

Prepare

npm install -g @angular/cli
npx @angular/cli new userDetails-client --style=css --routing=false --skip-tests

v17+

From Angular v17 onwards, Standalone is now the new default for the CLI. So when you create a new project, you won’t have any modules in it if you don’t specify anything.
However, it is still possible to create a module-based app by using the “—no-standalone” flag :

npx @angular/cli new userDetails-client --no-standalone --style=css --routing=false --skip-tests

Angular struct

Angular module

app/app.module.ts

Add system modules and user components

import pack:

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

declare Decorator:

// import HttpClientModule after BrowserModule.
    HttpClientModule,

Angular Component

app/component.ts

The root component.

When we need some services that need to be started at the beginning, we need to write code here.

Angular Html

app/app.component.html

View section.

To call root components and plug-and-play components, you need to write code here.

Angular Service

angular chrome run port

Generate service and model:

ng generate service user/user
ng generate class user/user --type=model

Every service must use Dependency Injection.

@Injectable(providedIn: 'root')

Creating observables

Use the Observable constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable’s subscribe() method executes.

getUsers(): Observable<UserModel[]>
postUser(userModel: UserModel): Observable<any> {// your code here}

call them

    this.userservice.getUsers().subscribe(
      data => {
        this.users = data;
        console.log(data);
    });

Angular Component

ng generate component sign-up
<app-sign-up></app-sign-up>

add component

app/app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    SignUpComponent
  ],
imports: [
    BrowserModule,
    ReactiveFormsModule
  ],

Appendix

Project code

The token is not used in the demo.

Reactive Forms

Use FormBuilder, FormGroup to implement applications.

see3, It should be noted that the verification part in html(sign-up.component.html) needs to refer to 4.

signUpForm.controls['xxx'].yyy

Authorization

实际应用中:使用用户名和密码登录,获得Token值。
chrome shot

最后,在http头添加token值, See《Adding and updating headers》.

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    Authorization: 'my-auth-token'
  })
};

Angular applies interceptors in the order that you provide them.
For example, consider a situation in which you want to handle the authentication
of your HTTP requests and log them before sending them to a server.
To accomplish this task, you could provide an AuthInterceptor service and then a LoggingInterceptor service.
Outgoing requests would flow from the AuthInterceptor to the LoggingInterceptor.
Responses from these requests would flow in the other direction, from LoggingInterceptor back to AuthInterceptor.
The following is a visual representation of the process:

angular auth

Ref

When you write @Injectable(providedIn: 'root') this means that the service in singletion 
for whole application and you can inject in anywhere in the application.
When you want to make service singleton only for an exact module, you need to assign 
your module as the parameter to the providedIn - @Injectable(providedIn: MyModule)
The only other action required in order to use the @Injectable decorated service is 
to import it and constructor inject it and that's it. 
No need to import it in the AppModule.
SSR is a good option for static websites whose content doesn't change frequently.