Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度5可观察,完成后返回_Angular_Observable - Fatal编程技术网

Angular 角度5可观察,完成后返回

Angular 角度5可观察,完成后返回,angular,observable,Angular,Observable,有助于观察角度5 我想对控制器隐藏复杂性;也就是说,它不必订阅可观察的。让服务具有所有的复杂性,并让它简单地将结果/有效负载返回给组件。但很明显,我陷入了时间问题。我觉得这应该是一个热门话题,但还没有找到答案。也许我做错了什么 //in the component.ts const allColors = this.auth.getColors(); //service call console.log(allColors); // returns undefined //in the ser

有助于观察角度5

我想对控制器隐藏复杂性;也就是说,它不必订阅可观察的。让服务具有所有的复杂性,并让它简单地将结果/有效负载返回给组件。但很明显,我陷入了时间问题。我觉得这应该是一个热门话题,但还没有找到答案。也许我做错了什么

//in the component.ts
const allColors = this.auth.getColors(); //service call
console.log(allColors); // returns undefined

//in the service.ts
getColors() {
  var myColors = "";

  var colors = this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
    .pipe(catchError(this.handleError));

  //
  colors.subscribe(
    res => {
      myColors = res.body;
    },
    error => {}
  );

  return myColors;
}
//在component.ts中
const allColors=this.auth.getColors()//服务电话
console.log(所有颜色);//返回未定义的
//在职
getColors(){
var myColors=“”;
var colors=this.http.get('http://localhost/Account/GetColors,httpOptions)
.pipe(catchError(this.handleError));
//
颜色。订阅(
res=>{
myColors=res.body;
},
错误=>{}
);
返回颜色;
}

我认为你不能做你想做的事情,因为在你的服务中的订阅没有得到解决之前,它不会向组件发送任何东西,在组件的执行过程中,它是未定义的,因为响应还没有到来

这就是回调函数被发明的原因。正确的方法是在组件中使用subscribe,因为您希望等待服务的响应

@Injectable()
export class ColorsResolver implements Resolve<any> {
     public constructor(private colorService: ColorService) {}

     public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
          return this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
                  .do((resp)=> this.colorService.setColor(resp));;
     }
}

很抱歉,我还不能使用评论,所以我必须做出回复。希望它能帮助你摆脱奥萨克所说的话。您必须在组件中订阅

为您效劳

getColors(): Observable<any> {

    let urlString = 'http://localhost/Account/GetColors'

    return this.http.get(urlString);
  }

您的方法何时返回?这是您需要回答的问题,为了避免在mycolor中充满任何东西之前它会返回的悬念,这就是异步编程的本质

您需要返回可观察的,并让它在结果可用时通知您。这种复杂性不能以您尝试的方式隐藏,您可以得到的最接近的方法是将回调函数传递到您的服务方法中,然后在结果可用时调用该函数,如下所示:

getColors(callback) {
    //...

    colors.subscribe(
       res => {
           callback(res.body);
       }
       //...
    );
}
但是你会错过很多很酷的功能,比如,你可以看到同样的东西

也许我做错了什么

//in the component.ts
const allColors = this.auth.getColors(); //service call
console.log(allColors); // returns undefined

//in the service.ts
getColors() {
  var myColors = "";

  var colors = this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
    .pipe(catchError(this.handleError));

  //
  colors.subscribe(
    res => {
      myColors = res.body;
    },
    error => {}
  );

  return myColors;
}
的确如此。使用可观察的和承诺的异步编程。我相信这是你问这个问题的唯一原因,你没有完全理解它们是如何工作的,所以你想把它抽象出来,这是你做不到的。另见


也就是说,您可以使用它来提供同步代码的外观

组件。ts

async ngOnInit() {
  const allColors = await this.auth.getColorsAsync(); //service call
  console.log(allColors); // returns color array
}
getColorsAsync(): Promise<color[]> {
  return this.http.get<color[]>('http://localhost/Account/GetColors', httpOptions)
    .pipe(catchError(this.handleError))
    .toPromise();
}
服务.ts

async ngOnInit() {
  const allColors = await this.auth.getColorsAsync(); //service call
  console.log(allColors); // returns color array
}
getColorsAsync(): Promise<color[]> {
  return this.http.get<color[]>('http://localhost/Account/GetColors', httpOptions)
    .pipe(catchError(this.handleError))
    .toPromise();
}
getColorsAsync():承诺{
返回此.http.get('http://localhost/Account/GetColors,httpOptions)
.pipe(catchError(this.handleError))
.toPromise();
}

我猜到了实际的类型。理想情况下,您应该尽可能使用强类型,而不是任何类型

我认为您可以用另一种方式

//in the component.ts
this.service.getColors(); //service call
console.log(this.service.allColors); // print the service property.  which will resolve after the oberservable resolve

//in the service.ts
@injectable()
export class Service {
  public allColors: any; //Public property to print.
  public getColors() {
    var myColors = "";

    var colors = this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
    .pipe(catchError(this.handleError));

    colors.subscribe(
      res => {
         this.allColors= res.body;
      },
      error => {}
     );

    return;
  }
}
//在component.ts中
this.service.getColors()//服务电话
console.log(this.service.allColors);//打印服务属性。在oberservable解析之后,哪个将解析
//在职
@可注射()
出口类服务{
public allColors:any;//要打印的公共属性。
公共颜色(){
var myColors=“”;
var colors=this.http.get('http://localhost/Account/GetColors,httpOptions)
.pipe(catchError(this.handleError));
颜色。订阅(
res=>{
这个.allColors=res.body;
},
错误=>{}
);
返回;
}
}

以下是我的做法:

this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
  .pipe(catchError(this.handleError))
  .subscribe(res => {
    console.log(res.body);
  });
this.http.get('http://localhost/Account/GetColors,httpOptions)
.pipe(catchError(this.handleError))
.订阅(res=>{
控制台日志(res.body);
});

您希望在使用服务之前使用
解析器和路由来预加载数据

冲突解决程序是一种异步操作,在激活其余路由之前完成。因此,您可以定义一个顶层路由,它不做任何事情,但包含用于获取颜色数据的解析器。我之所以说顶层,是因为我假设这是全局应用程序数据。如果此数据特定于某个功能,请将分解器放置在正确的路由路径中

const routes: Routes = [
    { 
       path: '',
       resolve: {
           Colors: ColorsResolver
       },
       children: [
             // your application routes here
       ]
    }
] 
colorsessolver
将从服务器获取颜色数据,然后将其分配给服务

@Injectable()
export class ColorsResolver implements Resolve<any> {
     public constructor(private colorService: ColorService) {}

     public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
          return this.http.get<any>('http://localhost/Account/GetColors', httpOptions)
                  .do((resp)=> this.colorService.setColor(resp));;
     }
}

现在,您可以在解析器完成后多次调用
getColor()
,而不阻塞它。

您无法简化到这一点。服务应该返回可观察对象本身。你可以在需要结果的地方订阅它,并在订阅回调中使用返回的值。我认为最好是包含观察值,而不是围绕它们工作,因为它们与角度的工作方式(以及其他原因)是不可分割的。似乎您正试图使其同步运行,而实际上它是一个异步进程。您所要做的实际上是在每次发出http请求时阻止整个应用程序的执行。可能的重复请注意,您仍然可以隐藏一些复杂性,这样服务的用户就不必处理
http
调用和
res.body
(在
map
操作员的帮助下)。