从Angular5中的服务器获取数据

时间:2018-07-02 10:02:12

标签: angular5

如何使用Angular5从Server获取数据。 我想在Angular5中获取通话

我尝试过:

getField (): Observable<b_fld[]> {
    return this.http.get<fld[]>(this.fieldUrl)
      .pipe(
        tap(fields => console.log(`fetched fields`))
      );
     }

1 个答案:

答案 0 :(得分:0)

我的方式是。 这是我的service.ts设置。

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

导入HttpClientHttpHeaders,然后按如下所示进行设置

accessToken;
apiUrl = environment.apiUrl; // Url Reads http://my-api.com 

// Only Needed if you have headers    
headers = new HttpHeaders()
    .set('Authorization', this.accessToken);

constructor(
    private http: HttpClient
) { }

getMyData(): Observable<any> {
    return this.http.get(
        this.apiUrl + '/my-data', // Url Reads http://my-api.com/my-data
        {headers: this.headers} // Include Headers If needed
    );
}

然后在我的compoinent.ts文件中看起来像这样。

import { MyService } from '../../services/my.service';

...
data;
...

constructor(
    ...
    private myService: MyService
    ...
) { }

async ngOnInit() {
    try {
        await this.getData();
    } catch (error) {
        console.log(error);
    }
    this.loaded = true;
}

async getData() {
    this.data = await this.getMyData();
}

// Get the Data
getMyData() {
    return new Promise((resolve, reject) => {
        this.myService.getMyData()
        .subscribe(
            data => {
                resolve(data);
            }, err => {
                reject(err);
            }
        );
    });
}