以下是一个关于Angular 7中服务和订阅的代码示例:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://api.example.com/data';
constructor(private http: HttpClient) { }
getData(): Observable {
return this.http.get(this.apiUrl);
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
template: `
Data:
- {{ item.name }}
`
})
export class MyComponent implements OnInit {
data: any[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(
(response: any) => {
this.data = response;
},
(error: any) => {
console.error('Error:', error);
}
);
}
}
在这个示例中,MyComponent组件通过在ngOnInit生命周期钩子中订阅数据服务的getData方法来获取数据。一旦数据返回,它会被分配给组件的data属性,然后可以在模板中使用。
请确保在app.module.ts中导入和提供DataService,并在HttpClientModule中导入HttpClient模块。