【发布时间】:2018-06-17 16:34:08
【问题描述】:
我正在尝试将数据从我的服务传递到我的组件,但无法这样做。以下是服务和组件的代码:
authService.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import{Http, RequestOptions,Headers} from '@angular/http'
import { Observable} from 'rxjs';
import { URLSearchParams,Response } from '@angular/http';
@Injectable()
export class AuthenticationService
{
constructor(private http: Http) { }
username:string = 'Admin';
password:string='livelink';
result :any;
login()
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('Username', this.username);
urlSearchParams.append('Password', this.password);
return this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
.subscribe((res:Response) =>
{
const data = res.json();
let headers = new Headers({
'OTCSTICKET': data['ticket']
});
let request_options = new RequestOptions({ headers:headers});
return this.http.get("http://localhost/otcs/cs.exe/api/v1/nodes/16236/output",request_options)
.subscribe(data =>
{
const report = data.json();
this.result = report;
console.log(this.result);
},
err => {
console.log(err);
}
)});
}
}
应用组件
import { Component } from '@angular/core';
import { AuthenticationService } from './authNew.servive';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import{Http, RequestOptions,Headers} from '@angular/http'
import { Observable} from 'rxjs';
import { URLSearchParams,Response } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
constructor(private authenticationservice:AuthenticationService)
{
this.authenticationservice.login().subscribe(res:Response =>
{
//somecode
}) ;
}
}
问题是当我尝试订阅 AppComponent 时,出现以下错误:
我知道我在这里做了一些非常愚蠢的事情。此外,我尝试在我的服务中使用地图而不是订阅 POST 和 GET 调用,但在这种情况下,我收到如下所示的错误:
我正在导入 'rxjs/add/operator/map';尝试使用地图时仍然出现错误,因此我考虑在服务本身内订阅,但这也无济于事。请帮助我了解如何对此进行排序并从我的服务中获取数据以在 AppComponent 中可用。
谢谢!
【问题讨论】:
-
为什么要同时订阅服务和组件?你真的只需要订阅组件。
-
好的,那我该如何修改我的服务,请你帮我理解一下。
-
您不应该使用嵌套订阅,而是使用扁平化操作符(switchMap、concatMap 或 flatMap)。出现错误是因为您已经订阅了该服务。你需要从你的服务中返回一个 Observable,然后在组件中订阅它。