Angular Observables:调用序列

时间:2017-07-26 15:39:36

标签: angular

我确定答案必须在那里,但我似乎无法找到我正在寻找的案例。我将在一个简单的组合示例中用非角度代码解释这一点。

在任何理性语言中,它看起来都像这样:

public Book CreateBook(Book theBook)
{
   //theBook is an object submitted by client code. 
   //it has 2 properties missing, call them “Property1” and
   //“Property2”

   //Property1 is filled in by calling one service
   theBook.Property1 = service1.GetMeMyValue();

   //Property2 is filled in automatically by the second service
   //and the updated value is returned.  Property1 MUST be filled in before
   //this is called.
   theBook = service2.SaveBook(theBook);

   return theBook;
}

Angular HTTP调用始终返回Observables。我找不到传递降压的神奇序列来让它发挥作用。我最接近Angular的说法是:

createBook(theBook : Book) : Observable<Book>
{
   return this.http.get("http://service1/someEndpoint")
      .map(item => {
         theBook[“Property1”] = item.json()[“Property1”];

         //something next here or outside?  Outside most likely.
      });
}

我尝试的任何东西都返回null / undefined,无论我对内部值做什么(或者我尝试外部返回的任何修改)。

我确信解决方案对于任何习惯Angular的人来说都是非常明显的(这比JavaScript的S&amp; M语法稍好一点),但它完全逃脱了我,我希望有人能够朝着正确的方向推动我。 / p>

1 个答案:

答案 0 :(得分:0)

<强>解

createBook(theBook : Book) : Observable<Book>
{
   return this.http.get("http://service1/someEndpoint")
      .flatmap(item => {

         //update Property1 with value from 1st GET
         theBook[“Property1”] = item.json()[“Property1”];

         //now create on 2nd service
         return this.http.post(
           “http://service2/createBook”,
           theBook,
           this.createRequestOptions(token))
           .map(response => response.json());
      });
}