在Angular中,本地服务默认只能接受字符串格式的数据。如果想要传递其他类型的数据,可以使用JSON.stringify()方法将其转化为字符串,然后在接收端使用JSON.parse()方法将其转化回原始类型。
以下是一个示例,展示如何在Angular中传递和接收一个对象:
在发送端的组件中:
import { HttpClient } from '@angular/common/http';
export class MyComponent {
constructor(private http: HttpClient) { }
sendData() {
const myObject = { name: 'John', age: 25 };
const dataString = JSON.stringify(myObject);
this.http.post('http://localhost:3000/api/myEndpoint', dataString)
.subscribe(response => {
console.log(response);
});
}
}
在接收端的服务中:
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
getData(dataString: string) {
const dataObject = JSON.parse(dataString);
console.log(dataObject);
}
}
请注意,这只是一个示例,你需要根据你的实际需求进行相应的修改。