在“我的Angular”应用中,我有一个从Web api获取数据的服务,URL地址如下:
/api/user/1
因此,数字前缀就是用户名。编写我的服务是为了获取activeUser
并将该信息绑定到另一个视图中。但是似乎没有数据通过吗?所以我的代码是:
service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(
private http: HttpClient,
) { }
public users: any = null;
public activeUser = null;
public getUsers(): Observable<any> {
if (this.users) {
return of(this.users);
} else {
return this.http.get<any>('/api/user').pipe(
tap(users => {
this.users = users;
})
);
}
}
public getUser(id): Observable<any> {
const existingUser = this.users ? this.users.results.find(user => user.id === id) : null;
if (existingUser && existingUser.addresses) {
return of (existingUser);
} else {
return this.http.get<any>(`/api/user/${id}`).pipe(
tap(user => {
if (existingUser) {
existingUser.address = user.address;
}
})
);
}
}
}
App component.ts
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
private elementRef : ElementRef
) {
}
public customer_id;
public user_id;
ngOnInit() {
this.customer_id = this.elementRef.nativeElement.getAttribute('activeCustomer');
this.user_id = this.elementRef.nativeElement.getAttribute('activeUser');
}
}
然后查看。ts
import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Request } from '../../models/request.model'
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import {debounceTime, distinctUntilChanged, map} from 'rxjs/operators';
import { AppComponent } from '../../../app.component';
import { nowService } from '../../services/servicenow.service';
import { UserService } from '../../../shared/services/user.service';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
private customer_id = this.appComponent.customer_id;
private user_id = this.appComponent.user_id;
HTML:
<p class="text-small text-gray mb-5">{{user_id}}</p>
所有这一切,但没有喜悦...
答案 0 :(得分:3)
this.http.get()
需要完整的API端点,即包括http://localhost:4412/api/user/
用于本地API。