我有一個 Angular (12.2.11) 應用程式,包括
- 應用組件
- 汽車組件
我已經在我的AppModuleas 中實作了路由:
const routes: Routes = [
{path: 'cars', component: CarsComponent},
];
我使用我的“CarsService”進行 API 呼叫并獲得汽車串列,所以一切正常。
但是在 AppComponent 中,我想呼叫/about端點以獲取 API 的版本,但這是行不通的。我的/about端點回傳我的 API 版本,我在 PostMan 中確認了這一點。這就是我正在做的:
創建的關于服務:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AboutService {
private baseUrl = "http://localhost:8080/myapi/v1/about";
constructor(private httpClient: HttpClient) { }
getAbout(): Observable<string> {
return this.httpClient.get<string>(`${this.baseUrl}`);
}
}
然后在我的 AppComponent 中,我實作了 OnInit,注入了 HttpClient,如:
import { Component, OnInit } from '@angular/core';
import { AboutService } from './services/about/about.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'My Angular App';
about: string;
constructor(private aboutService: AboutService) {}
ngOnInit(): void {
this.getAbout();
}
private getAbout() {
this.aboutService.getAbout().subscribe(data => {
this.about = data;
console.log(data);
},
error => {
console.log(error);
});
}
}
最后,在我的 AppComponent html 模板中:
<footer >
<div >
<span>{{about}}</span>
</div>
</footer>
The about information will not show. If I put some hardcoded text in the above span, the text will show. I added console.log() calls in above getAbout() to log received data but I dont see any log statements for that call. Also no error is logged. So, I guess it might be that routhing prevents execution of this method entirely.
How do I fetch data from app.component for above scenario?
UPDATE 1:
Updated above calls to console.log() to log received response data or error. It discovered that what I am getting is text rather than JSON and I think that is why nothing shows:
error:{error: SyntaxError: Unexpected token i in JSON at pos…
error:SyntaxError: message: 'Unexpected token i in JSON at position 0'}
text:'myapi v.1.0.0\nJdk v.11.0.10\nSpringboot v.5.3.9'
message:'Http failure during parsing for http://localhost:8080/myapi/v1/about'
As I am not planning to return JSON for /about endpoint but rather just plain text, is there a way to deal with this and get that text?
uj5u.com熱心網友回復:
我建議你使用AsyncPipe。所以它可能是這樣的: app.component.ts:
import { Component, OnInit } from '@angular/core';
import { AboutService } from './services/about/about.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'My Angular App';
about$: Observable<string>;
constructor(private readonly aboutService: AboutService) {}
ngOnInit(): void {
this.getAbout();
}
private getAbout(): void {
this.about$ = this.aboutService.getAbout();
}
}
app.component.html :
<footer >
<div >
<span>{{ about$ | async }}</span>
</div>
</footer>
相關問題 - 您是否在console.log(). 因為在提供的代碼中沒有傳遞引數。您是否嘗試在該行上放置斷點?
更新:
要從 HTTP 呼叫中獲取文本,您只需要設定Content-Typeheader 和responseType: 'text':
getAbout(): Observable<string> {
return this.httpClient.get<string>(`${this.baseUrl}`, {
headers: new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8'),
responseType: 'text'
});
}
uj5u.com熱心網友回復:
感謝@anjs 和@RuslanLekhan,他們上面的評論和回答幫助我查明了我犯的錯誤。
我將受人尊敬的 API 方法更改為回傳 JSON 物件而不是字串,并將代碼修改為:
export class AboutService {
private baseUrl = "http://localhost:8080/myapi/v1/about";
constructor(private httpClient: HttpClient) { }
getAbout(): Observable<About> {
return this.httpClient.get<About>(`${this.baseUrl}`);
}
}
上面About是包含有關 api 的資訊的模型,例如從 api 作為 JSON 物件回傳的 api 版本。
export class AppComponent implements OnInit {
title = 'My Angular App';
about: About;
constructor(private aboutService: AboutService) {}
ngOnInit(): void {
this.getAbout();
}
private getAbout() {
this.aboutService.getAbout().subscribe(data => {
this.about = data;
console.log(data);
},
error => {
console.log(error);
});
}
}
最后在模板頁腳中:
<footer >
<div >
<span>{{about.apiVersionNumber}}</span>
</div>
</footer>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335768.html
標籤:angular
