2017-11-15 24 views
1

私のGETリクエストは機能しますが、私のPUTリクエストはトリガーしていないようです。コンソールのconsole.logステートメントがコンソールに表示されるため、内部にある関数が確実に実行されます。 http PUTリクエスト内のconsole.logステートメントは、Google Chromeのコンソールまたは端末に表示されません。Express with Angular:PUTリクエストがトリガーされないのはなぜですか?

角度:

getCitiesSaved(): Observable<string[]> { 
    return this.http.get(this.url).map((data: Response) => { 
     this.currentCityList = data.json().cityAlerts; 
     return data.json().cityAlerts; 
    }); 
    } 

    addCity(cityName) { 
    let cityArr = this.currentCityList; 
    cityArr.push(cityName); 
    const body = JSON.stringify({ 
     id: this.userId, 
     cityAlerts: cityArr 
    }); 
    const headers = new Headers({ 'Content-Type': 'application/json' }); 
    console.log(body); 
    return this.http 
     .put(this.url, body, { headers: headers }) 
     .map((response: Response) => { 
     console.log('http put request ran in frontend'); 
     response.json(); 
     }) 
     .catch((error: Response) => { 
     this.errorService.handleSigninError(error.json()); 
     return Observable.throw(error.json()); 
     }); 
    } 

エクスプレス:

router.get('/users/:id', (req, res) => { 
    console.log('get user info'); 
    User.findOne({ 
    _id: req.params.id 
    }).exec((err, user) => { 
    if (err) { 
     return res.status(500).json({ 
     title: 'An error occured', 
     error: err 
     }); 
    } else { 
     console.log(user); 
     res.status(200).json(user); 
    } 
    }); 
}); 

router.put('/:users/:id', (req, res) => { 
    console.log('backend triggered'); 
    User.findOneAndUpdate(
    { 
     _id: req.params.id 
    }, 
    { $set: { cityAlerts: req.body.cityAlerts } }, 
    { upsert: true }, 
    function(err, newCityAlert) { 
     if (err) { 
     console.log(err); 
     } else { 
     console.log(newCityAlert); 
     res.send(newCityAlert); 
     } 
    } 
); 
}); 
+0

私のURLは「http:// localhost:3000/api/users/$ {this.userId}」です。 –

答えて

2

あなたは、要求が実行される前に観測可能にsubscribeを呼び出す必要があります。 mapsubscribeaddCity()に変更する必要があるようです。ドキュメントから

https://angular.io/guide/http

は、サブスクライブ()メソッドを注意してください。 HttpClientから返されるObservablesはすべて冷たいです。つまり、リクエストを作成するための青写真です。 subscribe()を呼び出すまでは何も起こりません。そのような呼び出しのたびに別のリクエストが行われます。たとえば、次のコードは、二度同じデータを持つPOSTリクエストを送信します。

彼らの例:

const req = http.post('/api/items/add', body); 
// 0 requests made - .subscribe() not called. 
req.subscribe(); 
// 1 request made. 
req.subscribe(); 
// 2 requests made. 

私はそれが役に立てば幸い - 私もこのつまずきました。

関連する問題